# @haddowg/json-api-client 中文文档

规范地址：https://npmcn.com/package/%40haddowg/json-api-client/

版本：1\.25\.0
npm 元数据更新时间：2026-11-16T23:01:29.412Z
中文译文更新时间：2026-11-17T05:50:23.299Z
软件包许可：MIT

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

原始 npm 页面：https://www.npmjs.com/package/%40haddowg/json-api-client
原文对照：https://npmcn.com/package/%40haddowg/json-api-client/?lang=original
项目主页：https://haddowg.github.io/json-api-ts/
源码仓库：https://github.com/haddowg/json-api-ts

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

- 包体积（解压后）：878 kB，21 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- Node.js 要求：\>=20
- 运行依赖：0 个
- peer 依赖：ajv ^8\.20\.0
- 首次发布：2026-07-13T10:50:32.247Z
- 最新版本发布：2026-11-16T23:01:29.041Z
- 近 30 天下载量：6295（2026-10-17 至 2026-11-15，npm 官方下载统计）
- 已发布版本数：29（近 12 个月 29 个）

## 中文简介

一个类型安全JSON:API客户端的通用,框架不可知运行时间. 由生成的描述符进行参数化.

## 安装

```sh
npm install @haddowg/json-api-client
```

也可以使用：`pnpm add @haddowg/json-api-client`、`yarn add @haddowg/json-api-client`、`bun add @haddowg/json-api-client`

## README

# @ haddowg/ json- api- 客户端

> **部分 [jsonapi.rest (英语)](https://jsonapi.rest/) 套间** - 完整、符合规格 JSON: API 1. 1 堆栈: 框架不可知 PHP [核心项目](https://github.com/haddowg/json-api)页:1 [符号捆绑](https://github.com/haddowg/json-api-symfony)页:1 [Laravel 软件包](https://github.com/haddowg/json-api-laravel)这个 **键入类型脚本 客户端**,由经过检测的OpenAPI 3.1合同捆绑在一起. 完整文档: **[(原始内容存档于2018-10-21) (韩语). haddog.github.io/json-api-ts](https://haddowg.github.io/json-api-ts/)**。 。 。 .

一个类型安全JSON:API客户端的通用,框架不可知运行时间. 参数:a 说明 [`@haddowg/json-api-codegen`](https://npmcn.com/package/%40haddowg/codegen) - 密码源读取您的API OpenAPI文档;此软件包执行去/序列化,水分化,和流畅的表面.

独立工作(`await client.albums.list()` 不需要框架。 用于 TanStack 查询缓存 + 正常化,加 [`@haddowg/json-api-query`](https://npmcn.com/package/%40haddowg/query)。 。 。 .

## 安装

```bash
pnpm add @haddowg/json-api-client
```

您一般不直接从这个软件包构造客户端—— 生成的模块 重新导出带有描述符的 `createClient`。下面的片段假设生成 `createClient` (见《大会正式记录,第五十八届会议,补编第6号》) [代码文件](https://npmcn.com/package/%40haddowg/codegen)) (中文(简体) ).

## 创建客户端

```ts
import { createClient } from './api/music.gen'

const client = createClient({
  baseUrl: 'https://music.example',
  // transport?: defaults to the global `fetch` adapter when omitted
  // headers?: per-request header provider (e.g. bearer auth); may be async
  headers: async () => ({ Authorization: `Bearer ${await getToken()}` }),
})
```

`ClientOptions`数字 :

| 选项 | 类型 | 页:1 |
| --- | --- | --- |
| `baseUrl` | `string` | 以生成的路径模板为基准解析 . |
| `transport` | `(req) => Promise<res>` | 运输接合; 默认为 a `fetch` 适配器. |
| `headers` | `() => HeadersInit | Promise<HeadersInit>` | 请求头提供者( arter auth等) . |
| `allowCrossOriginLinks` | `boolean` | 跟着a `$next()`编号 :`$prev()` 链接到另一个来源,没有 `headers`默认关闭. |
| `atomic` | `AtomicDescriptor | null` | 原子端点; 生成 `createClient` 把它接进去. |
| `validate` | `ValidationOption` | Opt-in-per-field验证接合(默认关闭). |

## 读取

资源读取返回 a **已实现** 值:属性和 `type`编号 :`id` 是平地的,可以假设的 道具(清理后可传播 /) `JSON.stringify`);信封挂出不可假定的 `$`\- 用户.

### 列出收藏 – 过滤 / s排序 / 包括 / 字段 / 页

```ts
const albums = await client.albums.list({
  filter: { status: 'released' },
  sort: '-releasedAt',
  include: ['artist'], // widens `artist` to a hydrated resource in the result type
  fields: { albums: ['title', 'status', 'artist'] }, // sparse — other attrs are statically absent
  page: { number: 1 },
})

albums[0]!.title // string
albums[0]!.artist?.name // hydrated artist resource (its attributes are typed)
albums.$page.kind // 'page' (typed from the descriptor's paginator)
albums.$meta?.['page'] // raw top-level meta
```

> 保留在 `include` 也必须留在 `fields` 用于该类型,或缩小 关闭结果类型.

### 获得一个水合化合物文件

```ts
const ok = await client.albums.get('1', { include: ['artist', 'tracks'] })

ok.title // string
ok.$self // resource-level self link (non-enumerable)
ok.tracks // the to-many `tracks` is a hydrated augmented array of track resources
```

### 资源级 `$`\- 用户

实际资源携带(所有不可承担):

-   `$meta` 资源级元a
-   `$links` 编号 : `$self` 资源级链接(`$self` 这是 `self` 链接快手)
-   `$document` ——共享,修剪顶层 `{ jsonapi, meta, links }`
-   `$raw` ——原JSON:API资源对象(逃出舱口)
-   `$rel(name)` —— 说 `{ data, links, meta }` 用于关系(仅链接关系+内向)

### 跟随关系

```ts
// The related RESOURCES (full objects): GET /albums/1/tracks
const tracks = await client.albums
  .id('1')
  .rel('tracks')
  .related({ page: { size: 2 } })
tracks.map((t) => t.title)
tracks.$page.kind

// The LINKAGE (resource identifiers): GET /albums/1/relationships/tracks
const linkage = await client.albums.id('1').rel('tracks').get()
```

### 单子

单通类型为每个调用者在一条路径上提供一种资源,没有ID(`/inbox`) (中文(简体) ). 它的访问器是 处理该资源,没有 `list`, (中文(简体) ), `create`, (中文(简体) ), `id()` 或者说 `delete`。更新机构需要 资源为 id,所以输入带有:

```ts
const inbox = await client.inboxes.get() // GET /inbox
await client.inboxes.update({ id: inbox.id, seenUpTo: new Date().toISOString() }) // PATCH /inbox
const owner = await client.inboxes.owner.related() // GET /inbox/owner
```

### 多个边缘的关键数据

成员 `belongsToMany` 将它的尖端支点放在下面 `$pivot` (类糖) 结束 `meta.pivot`; 另一父的同一资源带有不同的中枢.

```ts
const ordered = await client.playlists.id(playlistId).rel('orderedTracks').related()
ordered[0]!.$pivot?.['position'] // edge-local pivot data
```

### `withCount` (可计数配置)

`withCount` 受寄出的操作的计数符限制: `list`,相关 读取,以及 `get`, (中文(简体) ), `create` 财务报告和审定财务报表 `update` 服务器在那里记录它。 一个资源没有 收藏,所以这三人从来不拿 `_self_`。客户端在其中谈判可计数配置文件 `Accept` 当 `withCount` 已存在.

```ts
const albums = await client.albums.list({ withCount: ['tracks'] })
albums[0]!.$count('tracks') // number: the list asked to count tracks
```

服务器将每个计数放在关系对象中 `meta.total`。 。 。 . `$count(name)` 读出来 资源,即使关系上没有数据, 和很多关系阵列 与 `$count`两者都是 `undefined` 当服务器发送的号码没有限制时.

### `relatedQuery` (关系查询简介)

在服务器的文档中, `relatedQuery` 过滤和排序资源的关系 操作的答案为: `list`, (中文(简体) ), `get`, (中文(简体) ), `create`, (中文(简体) ), `update`,则 `.related()` 读取关系 超过一个类型,而动作以资源响应。 按关系名键,每个 条目 `filter` 财务报告和审定财务报表 `sort` 将关系本身的相关读取,不 `sort` 编号 倒计时。 客户端在其中谈判配置文件 `Accept`在可计数的旁边,当 `withCount` 也准备好了.

```ts
const runs = await client['campaign-template-runs'].list({
  withCount: ['items'],
  relatedQuery: { items: { filter: { state: 'failed' } } },
})
runs[0]!.$count('items') // the run's failed items
```

### 相位光标( L)

所有三个收藏表面(上层列表,相關相關相關相關相關相關相關相關相關相關相關相關相關相關相關相關相關相關相關相關相關相關相關相關相關相關相關相關相關相關相關相 揭发同样的 `$page` + 键 `$next()` 编号 : `$prev()`导航 **无倒数安全** ——驱动 链接存在,不是全部。 光标算法只是算法 `kind`; 页使用 `page[after]` 编号 : `page[before]` 编号 : `page[size]` 查询参数并用 `$next()`数字 :

```ts
let page = await client.tracks.list({ page: { size: 50 } })
while (page) {
  for (const track of page) {
    /* … */
  }
  page = await page.$next() // undefined when there is no next link
}
```

## 写作

平面ergonomic 输入——客户端构建了JSON:API文档. 创建/ 更新返回 已实现的资源; 删除解析 `void`。 。 。 .

```ts
// POST /albums — `id` is required/optional/forbidden per the spec's per-type policy.
const created = await client.albums.create({ title: 'Kid A', status: 'released' })

// PATCH /albums/1 — a partial patch.
const updated = await client.albums.id('1').update({ title: 'OK Computer (Remaster)' })

// DELETE /albums/1 — resolves void (a 204).
await client.albums.id('1').delete()
```

创建/ 更新接受可选的第二个参数 `{ include?, fields? }` 来塑造已实现的 反应,就像读取.

### 关系突变

人际关系暴露 `add` 编号 : `remove` 编号 : `replace`; 一对一曝光 `set(ref | null)`A级 动词只有在关系端点广告时才会出现(描述者对关系的描述) `mutations` 旗,来自捆绑 `cannotAdd` 编号 : `cannotRemove` 编号 : `cannotReplace` + 键 端点曝光)——被禁动词为编译出错,不是运行时出奇.

```ts
// to-many: POST / DELETE / PATCH .../relationships/tracks
await client.albums
  .id('1')
  .rel('tracks')
  .add([{ type: 'tracks', id: '4' }])
await client.albums
  .id('1')
  .rel('tracks')
  .remove([{ type: 'tracks', id: '4' }])
await client.albums
  .id('1')
  .rel('tracks')
  .replace([
    { type: 'tracks', id: '1' },
    { type: 'tracks', id: '3' },
  ])

// to-one: PATCH .../relationships/artist
await client.albums.id('1').rel('artist').set({ type: 'artists', id: '2' })
await client.albums.id('1').rel('artist').set(null) // clear
```

> **动词/ 关系碰撞 :** 关系可以通过 `.rel('name')` (和,对于普通 案件,由姓名直接卸下。 以保留动词命名的关系(`get`, (中文(简体) ), `update`, (中文(简体) ), `delete`, (中文(简体) ), `actions`,.)是被阴影所笼罩的——代码在构建时间发出警告,你通过它到达 `.rel('name')`。 。 。 .

## 自定义动作

通过 `.actions.<name>`: 从类型访问器中扫描到收集范围, 资源范围 关闭手柄( e)`.id(id)`) (中文(简体) ). 身体的形状遵循动作的宣告 `input` (单位:千美元)`none` 编号 : `document` 编号 : `raw`页:1 `document` 产出已实现,a `none` 输出解析 `undefined`。 。 。 .

```ts
// Resource-scoped, document in / document out.
const reissued = await client.albums.id('1').actions.reissue({
  releasedAt: '2001-10-01T00:00:00+00:00',
})

// Collection-scoped, no input.
const summary = await client.albums.actions.summary()
```

## 原子作业

`client.atomic(tx => …)` 记录行动顺序,并把它们作为全部或无记录的批次公布 原子ext介质类型). A 类 `tx.create(...)` 控件 **双倍为 `lid` 参考**,所以刚刚创建 资源线通入后期行动,没有服务器代号。 结果按操作索引打入位置.

```ts
const [artist, geogaddi] = await client.atomic((tx) => {
  const newArtist = tx.create({ type: 'artists', name: 'Boards of Canada' })
  const newAlbum = tx.create({ type: 'albums', title: 'Geogaddi', artist: newArtist })
  return [newArtist, newAlbum] as const
})

artist.data.id // '99'
geogaddi.data.title // 'Geogaddi'
```

`tx` 还揭露 `tx.update({ type, id, …fields })` 财务报告和审定财务报表 `tx.delete({ type, id } | ref)`调用 `client.atomic` 在一个不会暴露原子端点的服务器上.

## 错误

非-2xx 投出一个键 `JsonApiError` 携带 `status` + 键 `errors: JsonApiErrorObject[]`,与 表达式状态匹配器和指针分组 :

```ts
import type { JsonApiError } from '@haddowg/json-api-client'

try {
  await client.albums.create({ title: '' })
} catch (e) {
  const error = e as JsonApiError
  error.isUnprocessable() // 422 (alias: isValidationError())
  // Server pointers (`/data/attributes/title`) are remapped to your FLAT input path (`title`).
  error.byPath()['title']?.[0]?.detail // 'must not be blank'
}
```

状态匹配者 : `hasStatus(n)`, (中文(简体) ), `is4xx()`, (中文(简体) ), `is5xx()`, (中文(简体) ), `isBadRequest()` / 400, (中文(简体) ), `isUnauthorized()` 第401次会议, `isForbidden()` 第403次会议, `isNotFound()` 第404次会议, `isNotAcceptable()` 第406次会议, `isConflict()` 第409次会议, `isUnsupportedMediaType()` 第415次会议, `isUnprocessable()` 编号 : `isValidationError()` 第422次会议, `isRateLimited()` 第429页.

`byPath()` 按平面输入路径分组出错(返回原始指针,然后查询) `parameter`——形式/验证UX的支付. 每个错误都保持原生 `source.pointer` 作为 逃出舱门; 原子错误还带有 `opIndex`。 。 。 .

`hasErrorCode(err, code)` 当 `err` 是一个 `JsonApiError` 及其任何错误对象 携带 `code`。生成的客户端导出一个与其服务器文件绑定的版本 `ErrorCode` 结合,因此错误的密码无法编译,匹配缩小到 `JsonApiError<ErrorCode>`。 。 。 .

> 解析但违反 JSON: API 信封形状的回复( 不是文档, 是成员) 缺少 `type`编号 :`id`扔出一个 `StructuralGuardError` 不同于服务器报告 `JsonApiError`。这些轻质结构警卫总是在运行;每个战地完全验证是选入 (下关.

## 运输

运输是很小的 `fetch`\- 形状的函数,所以任何冲动(内在) `fetch`,undici,一个轴 适配器,或测试模拟器)下降:

```ts
import type {
  JsonApiTransport,
  TransportRequest,
  TransportResponse,
} from '@haddowg/json-api-client'

const transport: JsonApiTransport = async (req: TransportRequest): Promise<TransportResponse> => {
  const res = await myHttpLib(req.method, req.url, { headers: req.headers, body: req.body })
  return { status: res.status, headers: res.headers, body: res.text }
}

const client = createClient({ baseUrl: 'https://music.example', transport })
```

背心在这里被故意超出范围——运输(或称"坦斯塔克地层")拥有.

`req.signal` 当呼叫者通过一个 `signal` 改为:`client.albums.list({ signal })` 或者说 `$next({ signal })`) (中文(简体) ). 将其转发到您的 HTTP 库, 以便取消请求 默认 `fetch` 运输经过 `fetch`。 。 。 .

两个可选成员只针对非JSON:API媒体类型的自定义动作. 发送 `req.rawBody` 如设定时: 二进制, `FormData` 或者说 `URLSearchParams` 替换 `req.body`时 `req.responseType` 实值 `'blob'` 或者说 `'arraybuffer'`,读取成功的答复 输入 `binary` 和类型的离开 `body` 空; 将错误响应读作文本 `body` 作为 常规。 这个 `fetch` 两者兼有.

## Opt- in 验证

核心运行时间信任电线(你拥有两端;信封无变化),只运行 轻质结构警卫。 完全逐地验证为 **选入** 通过 `validate?` 选项,由 按类型输入的密码源 `schemas` 地图。 验证引擎由你带来,从来没有在 核心 dep 树 .

### 用捆绑的相接器

`ajv` 是一个可选的对等依赖;适配方生活在 `@haddowg/json-api-client/ajv` 子路径,所以导入主条目 从来没有拉ajv英寸.

```bash
pnpm add ajv
```

```ts
import Ajv2020 from 'ajv/dist/2020'
import { createClient } from './api/music.gen'
import { createAjvValidator } from '@haddowg/json-api-client/ajv'
import { schemas } from './api/music.schemas.gen' // the codegen's `--schemas` output

// The bundle emits JSON Schema 2020-12, so use `Ajv2020`. `strict: false` tolerates the
// schemas' `x-enum-*` annotations; `allErrors` aggregates every failing field.
const ajv = new Ajv2020({ allErrors: true, strict: false, validateFormats: false })

const client = createClient({
  baseUrl: 'https://music.example',
  validate: createAjvValidator(ajv, schemas),
})
```

现在每个电线资源都被验证出来 `schemas[type]`; 捆绑不覆盖的类型是 跳过( 快速的部分覆盖) 。 失败投出 `AjvValidationError` 随身携带 失败 `{ type, id?, pointer, keyword, message }`。 。 。 .

### 用你自己的发动机

`validate` 并接受由 chema 驱动的配置 `{ schemas, validator }` 或裸体 `(resource, schema) => void` 拥有自己的计划查看符 :

```ts
const client = createClient({
  baseUrl: 'https://music.example',
  validate: (resource) => {
    // throw on an invalid resource; return for a valid one
  },
})
```

## 许可证

麻省理工学院

## 常见问题

### @haddowg/json-api-client 是什么？

一个类型安全JSON:API客户端的通用,框架不可知运行时间\. 由生成的描述符进行参数化\.

### 如何安装 @haddowg/json-api-client？

在项目目录运行 npm install @haddowg/json-api-client，或使用 pnpm add / yarn add / bun add。

### @haddowg/json-api-client 支持 TypeScript 吗？

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

### @haddowg/json-api-client 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @haddowg/json-api-client 需要什么版本的 Node\.js？

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

### @haddowg/json-api-client 可以商用吗？

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

### @haddowg/json-api-client 的下载量有多少？

根据 npm 官方下载统计，@haddowg/json-api-client 在 2026/10/17 – 2026/11/15 这 30 天内被下载 6,295 次，日均约 210 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @haddowg/json-api-client 还在维护吗？

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

