# @jsondrop/core 中文文档

规范地址：https://npmcn.com/package/%40jsondrop/core/

版本：0\.1\.0
npm 元数据更新时间：2026-11-01T13:48:59.325Z
中文译文更新时间：2026-11-01T14:32:08.420Z
软件包许可：MIT

本文由上游 README 机器翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40jsondrop/core
原文对照：https://npmcn.com/package/%40jsondrop/core/?lang=original
项目主页：https://github.com/valicm/jsondrop/tree/main/packages/core#readme
源码仓库：https://github.com/valicm/jsondrop

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：152 kB，48 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- Node.js 要求：\>=20\.19
- 运行依赖：0 个
- 首次发布：2026-11-01T13:48:03.338Z
- 最新版本发布：2026-11-01T13:48:59.145Z
- 已发布版本数：2（近 12 个月 2 个）

## 中文简介

Drupal JSON:API的一个类型化的、与框架无关的客户端。

## 安装

```sh
npm install @jsondrop/core
```

也可以使用：`pnpm add @jsondrop/core`、`yarn add @jsondrop/core`、`bun add @jsondrop/core`

## README

# @jsondrop /核心

Drupal JSON:API的一个类型化的、与框架无关的客户端。没有依赖关系。

```sh
npm install @jsondrop/core
```

## 使用

```ts
import { JsonApiClient, clientCredentials } from '@jsondrop/core';

const drupal = new JsonApiClient({
  baseUrl: 'https://cms.example.com',
  auth: clientCredentials({ clientId: '…', clientSecret: '…', scope: 'content:read' }),
});

const articles = await drupal.getCollection('node--article', {
  query: {
    include: ['field_image', 'uid'],
    filter: { status: 1 },
    sort: ['-created'],
    page: { limit: 10 },
  },
});

articles[0].field_image; // the included file--file, with relationshipMeta.alt
```

响应是反序列化的：属性和关系位于一个响应上 对象和关系被其包含的资源所替换 (递归)。未包含目标的关系是存根 （`{ id, type, stub: true }`,看 `isStub`）。

## 输入你的资源

通过声明合并注册一次资源类型：

```ts
import type { ResourceBase, ToOne, ToMany } from '@jsondrop/core';

interface NodeArticle extends ResourceBase<'node--article'> {
  title: string;
  body: { value: string; processed: string } | null;
  field_tags: ToMany<TaxonomyTerm>;
  field_image: ToOne<File>;
}

declare module '@jsondrop/core' {
  interface ResourceTypes {
    'node--article': NodeArticle;
  }
}

const article = await drupal.getResource('node--article', id); // NodeArticle
```

## API

**资源**： `getResource`， `getCollection`， `getPage` (与 `next()`)， `iterate` (异步,遵循 `next` 链接), `createResource`， `updateResource`， `deleteResource`， `uploadFile`.

**请求** 相对于API前缀，对于自定义资源： `get`， `post`， `patch`， `delete`， `request`． 它们返回原始文档 与 `data`， `meta`， `links`， `status` 和 `headers`.

**选项** （客户端，每个请求一些）：

| 选项 |  |
| --- | --- |
| `baseUrl` | 网站的起源 |
| `apiPrefix` | 默认的 `/jsonapi` |
| `locale`， `defaultLocale` | 语言路径前缀(`/de/jsonapi/…`） |
| `auth` | `bearer`， `basic`， `sessionCookie`， `clientCredentials`，或者你自己的 `AuthStrategy`； `false` 每个请求 |
| `headers` | 对象或（async）函数 |
| `resourcePaths` | Type→path，对于用JSON重命名的类型：API Extras |
| `fetchOptions` | 传递给 `fetch`,如。 `{ next: { revalidate: 60, tags: ['node:1'] } }` |
| `onResponse` | 在每个请求之后调用，用于记录日志 |

## 用户登录（OAuth）

`OAuthClient` 运行simple\_oauth 6。x的授权代码流与PKCE 并刷新令牌(6)。X删除了密码和隐式授权)：

```ts
import { OAuthClient } from '@jsondrop/core';

const oauth = new OAuthClient({ baseUrl, clientId, clientSecret, redirectUri, scope: 'openid profile' });

// 1. Redirect to Drupal; keep state + codeVerifier in an httpOnly cookie.
const { url, state, codeVerifier } = await oauth.startLogin();
// 2. On the redirect back: checks the state, exchanges the code.
const tokens = await oauth.finishLogin({ code, state: returnedState }, { state, codeVerifier });
// 3. Store the tokens server-side; requests as the user:
const asUser = drupal.extend({ auth: oauth.strategy(tokenStore) });
```

该策略在令牌过期之前和401之后刷新令牌。 刷新令牌是一次性使用的，所以并发刷新共享一个请求： 保持一个 `OAuthClient` 当Drupal拒绝刷新令牌时 存储被清空并抛出请求 `LoginRequiredError`：将用户发送到 重新登录。 `oauth.userInfo(accessToken)` 读取OpenID Connect声明。 看到 [例7](https://npmcn.com/package/examples/07-user-login.ts).

**重命名资源** （JSON:API Extras）： API的入口点列出了每个 类型的路径，因此让客户端在启动时读取它们一次，而不是 手工映射它们：

```ts
const drupal = await new JsonApiClient({ baseUrl }).withDiscoveredPaths();
drupal.resourcePath('products'); // '/products', as the site configures it
```

`client.extend({ headers })` 派生一个添加标题（购物车）的客户端 令牌，一个市场)，并共享父级的认证和令牌缓存。

**错误**：非2xx响应抛出 `JsonApiError` 与 `status`， `errors` 还有文件；它的 `message` Drupal的 `detail`． 在401上，策略 使用缓存令牌更新，请求重试一次。

**链接**：来自文档(`links.next`)发送至 `baseUrl`的起源，所以Drupal背后的一个代理，建立链接与 内部主机仍然工作，凭证永远不会到其他地方。

**查询** 也接受预构建的字符串，例如来自drupal-jsonapi-params。

## 常见问题

### @jsondrop/core 是什么？

Drupal JSON:API的一个类型化的、与框架无关的客户端。

### 如何安装 @jsondrop/core？

在项目目录运行 npm install @jsondrop/core，或使用 pnpm add / yarn add / bun add。

### @jsondrop/core 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @jsondrop/core 支持 ESM 还是 CommonJS？

以 ES Module 形式发布，推荐使用 import 引入。在 CommonJS 项目中，Node\.js 20\.19\+ / 22\.12\+ 可以直接 require\(\) 不含顶层 await 的 ES Module，更早的版本需要改用动态 import\(\)。

### @jsondrop/core 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>=20\.19。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @jsondrop/core 可以商用吗？

@jsondrop/core 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @jsondrop/core 还在维护吗？

最新版本 0\.1\.0 发布于 2026/11/01（1 天前）；至今共发布 2 个版本，其中过去 12 个月发布了 2 个；首次发布于 2026/11/01。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

