@haddowg/json-api-client

中文文档
1.25.0发布于 2026/11/17MITTypeScriptESM + CJS零依赖构建来源已验证近 30 天下载 6295

Generic, framework-agnostic runtime for a typesafe JSON:API client. Parameterised by a generated descriptor.

原始使用文档
文档目录22 节
  1. Install
  2. Creating a client
  3. Reads
  4. List a collection — filter / sort / include / fields / page
  5. Get one — with a hydrated compound document
  6. Resource-level $ -accessors
  7. Follow a relationship
  8. A singleton
  9. Pivot data on a many-to-many edge
  10. withCount (the Countable profile)
  11. relatedQuery (the Relationship Queries profile)
  12. Pagination & cursor
  13. Writes
  14. Relationship mutation
  15. Custom actions
  16. Atomic operations
  17. Errors
  18. Transport
  19. Opt-in validation
  20. With the bundled ajv adapter
  21. With your own engine
  22. License

@haddowg/json-api-client

Part of the jsonapi.rest suite — a complete, spec-compliant JSON:API 1.1 stack: a framework-agnostic PHP core, a Symfony bundle, a Laravel package, and this typed TypeScript client, bound together by one conformance-tested OpenAPI 3.1 contract. Full documentation: haddowg.github.io/json-api-ts.

The generic, framework-agnostic runtime for a typesafe JSON:API client. Parameterised by a descriptor emitted by @haddowg/json-api-codegen — the codegen reads your API's OpenAPI document; this package does the de/serialisation, hydration, and the fluent surface.

Works standalone (await client.albums.list() needs no framework). For TanStack Query caching + normalization, add @haddowg/json-api-query.

Install

pnpm add @haddowg/json-api-client

You generally don't construct the client from this package directly — the generated module re-exports a descriptor-bound createClient. The snippets below assume that generated createClient (see the codegen docs).

Creating a client

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:

OptionTypeNotes
baseUrlstringBase URL the generated path templates resolve against.
transport(req) => Promise<res>The transport seam; defaults to a fetch adapter.
headers() => HeadersInit | Promise<HeadersInit>Per-request header provider (bearer auth, etc.).
allowCrossOriginLinksbooleanFollow a $next()/$prev() link to another origin, sent without headers. Off by default.
atomicAtomicDescriptor | nullAtomic endpoint; the generated createClient threads it in.
validateValidationOptionOpt-in per-field validation seam (off by default).

Reads

A resource read returns a materialised value: attributes and type/id are flat, enumerable props (clean to spread / JSON.stringify); the envelope hangs off non-enumerable $-accessors.

List a collection — filter / sort / include / fields / page

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

A relation kept in include must also stay in the fields set for that type, or it is narrowed off the result type.

Get one — with a hydrated compound document

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

Resource-level $-accessors

A materialised resource carries (all non-enumerable):

  • $meta — resource-level meta
  • $links / $self — resource-level links ($self is the self link shorthand)
  • $document — the shared, trimmed top-level { jsonapi, meta, links }
  • $raw — the original JSON:API resource object (escape hatch)
  • $rel(name) — { data, links, meta } for a relation (links-only relations + introspection)

Follow a relationship

// 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()

A singleton

A singleton type serves each caller one resource at a path with no id (/inbox). Its accessor is a handle on that resource, with no list, create, id() or delete. The update body needs the resource's id, so the input carries it:

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

Pivot data on a many-to-many edge

Each member of a belongsToMany to-many carries its per-edge pivot under $pivot (typed sugar over meta.pivot); the same resource in another parent carries a different pivot.

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

withCount (the Countable profile)

withCount is constrained to the count tokens of the operation that sends it: list, a related read, and get, create and update where the server documents it there. One resource has no collection, so those three never take _self_. The client negotiates the Countable profile in Accept automatically when withCount is present.

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

The server puts each count in the relationship object's meta.total. $count(name) reads it off the resource, even when the relationship carries no data, and a to-many relationship array has the same value as $count. Both are undefined when the server sent no finite number.

relatedQuery (the Relationship Queries profile)

Where the server documents it, relatedQuery filters and sorts a relationship of the resources an operation answers with: list, get, create, update, the .related() read of a relation over one type, and an action answering with a resource. It's keyed by relation name, and each entry's filter and sort take what the relation's own related read takes, with no sort on a to-one. The client negotiates the profile in Accept, beside the Countable one when withCount is set too.

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

Pagination & cursor

All three collection surfaces (top-level lists, related collections, to-many relationship arrays) expose the same $page + $next() / $prev(). Navigation is count-free-safe — driven by link presence, not a total. Cursor pagination is just a paginator kind; page with page[after] / page[before] / page[size] query params and walk it with $next():

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
}

Writes

Flat ergonomic input — the client builds the JSON:API document. Create / update return the materialised resource; delete resolves void.

// 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()

Create / update accept an optional second arg { include?, fields? } to shape the materialised response, exactly like a read.

Relationship mutation

A to-many relation exposes add / remove / replace; a to-one exposes set(ref | null). A verb is present only when the relation's endpoint advertises it (the descriptor's per-relation mutations flags, derived from the bundle's cannotAdd / cannotRemove / cannotReplace + endpoint exposure) — a forbidden verb is a compile error, not a runtime surprise.

// 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

Verb / relation collision: relations are reachable via .rel('name') (and, for the common case, by name directly off the handle). A relation named like a reserved verb (get, update, delete, actions, …) is shadowed — the codegen warns at build time and you reach it via .rel('name').

Custom actions

Actions are reached via .actions.<name>: collection-scoped off the type accessor, resource-scoped off a handle (.id(id)). The body shape follows the action's declared input (none / document / raw); a document output is materialised, a none output resolves undefined.

// 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()

Atomic operations

client.atomic(tx => …) records ops in order and posts them as one all-or-nothing batch (the atomic ext media type). A tx.create(...) handle doubles as a lid ref, so a just-created resource wires into later ops without a server id. Results are typed positionally by op index.

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 also exposes tx.update({ type, id, …fields }) and tx.delete({ type, id } | ref). Calling client.atomic on a server that exposes no atomic endpoint throws.

Errors

A non-2xx throws a typed JsonApiError carrying status + errors: JsonApiErrorObject[], with expressive status matchers and pointer grouping:

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'
}

Status matchers: hasStatus(n), is4xx(), is5xx(), isBadRequest() /400, isUnauthorized() /401, isForbidden() /403, isNotFound() /404, isNotAcceptable() /406, isConflict() /409, isUnsupportedMediaType() /415, isUnprocessable() / isValidationError() /422, isRateLimited() /429.

byPath() groups errors by the flat input path (falling back to the raw pointer, then the query parameter) — the payoff for form/validation UX. Each error keeps its raw source.pointer as an escape hatch; atomic errors also carry an opIndex.

hasErrorCode(err, code) is true when err is a JsonApiError and any of its error objects carries code. A generated client exports a version bound to its server's documented ErrorCode union, so a misspelt code fails to compile and a match narrows to JsonApiError<ErrorCode>.

A response that parses but violates the JSON:API envelope shape (not a document, a member missing type/id) throws a StructuralGuardError — distinct from a server-reported JsonApiError. These light structural guards are always on; full per-field validation is opt-in (below).

Transport

The transport is a tiny fetch-shaped function, so any impl (native fetch, undici, an axios adapter, or a test mock) drops in:

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 })

Retries are deliberately out of scope here — the transport (or the TanStack layer) owns them.

req.signal is set when the caller passed a signal to a read (client.albums.list({ signal }) or $next({ signal })). Forward it to your HTTP library so the request can be cancelled; the default fetch transport passes it to fetch.

Two optional members matter only for custom actions with non-JSON:API media types. Send req.rawBody as is when it's set: a binary, FormData or URLSearchParams body in place of req.body. When req.responseType is 'blob' or 'arraybuffer', read a successful response into binary as that type and leave body empty; read an error response as text in body as usual. The fetch transport does both.

Opt-in validation

The core runtime trusts the wire (you own both ends; the envelope is invariant) and only runs the light structural guards. Full per-field validation is opt-in via the validate? option, fed by the codegen-emitted per-type schemas map. The validation engine is brought by you, never in the core dep tree.

With the bundled ajv adapter

ajv is an optional peer dependency; the adapter lives at the @haddowg/json-api-client/ajv sub-path, so importing the main entry never pulls ajv in.

pnpm add ajv
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),
})

Every wire resource is now validated against schemas[type]; a type the bundle does not cover is skipped (graceful partial coverage). A failure throws an AjvValidationError carrying every failing { type, id?, pointer, keyword, message }.

With your own engine

validate also accepts the schema-driven config { schemas, validator } or a bare (resource, schema) => void validator that owns its own schema lookup:

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

License

MIT

版本与发布记录

@haddowg/json-api-client 共发布 29 个版本,首次发布于 2026/07/13;过去 12 个月发布了 29 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
1.25.0latest2026/11/17今天
1.24.02026/11/17今天
1.23.02026/11/16今天
1.22.02026/11/133 天前
1.21.02026/11/134 天前
1.20.02026/11/124 天前

关于 @haddowg/json-api-client 的常见问题

@haddowg/json-api-client 是什么?

Generic, framework-agnostic runtime for a typesafe JSON:API client. Parameterised by a generated descriptor.

如何安装 @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 和提交记录判断。