@haddowg/json-api-query

中文文档
1.7.2发布于 2026/11/17MITTypeScriptESM + CJS构建来源已验证近 30 天下载 4604

TanStack Query bindings for the JSON:API client: option/key factories + type:id cache normalization.

原始使用文档
文档目录8 节
  1. Install
  2. Binding the client
  3. Reads — query option factories
  4. The query-key factory
  5. Normalization ( type:id write-through patching)
  6. Writes — mutation option factories
  7. Worked example (query-core directly)
  8. License

@haddowg/json-api-query

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.

TanStack Query bindings for the @haddowg/json-api-client runtime: query/mutation option factories (not pre-bound hooks), a deterministic query-key factory, and bespoke type:id write-through cache normalization.

Because the surface is option factories over @tanstack/query-core, one binding covers React / Vue / Svelte / Solid — you pass the returned { queryKey, queryFn } / MutationOptions to your framework's useQuery / useMutation.

Install

pnpm add @haddowg/json-api-query @tanstack/query-core

@tanstack/query-core is a peer dependency.

Binding the client

The read factories accept Client<D, A> and the write factories Client<D, A, W> — neither carries the client's custom-action types (actions aren't cacheable resources). The generated createClient returns a client that also carries action types, so view it through the action-agnostic Client types at the query boundary — one cast per surface:

import type { Client } from '@haddowg/json-api-client'
import { createClient } from './api/music.gen'
import type { Attributes, ResourceMap, WriteAttributes } from './api/music.gen'

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

type ReadClient = Client<ResourceMap, Attributes>
type WriteClient = Client<ResourceMap, Attributes, WriteAttributes>

Reads — query option factories

Each factory returns a plain { queryKey, queryFn }, structurally compatible with query-core's QueryOptions, preserving the client's full static narrowing (include widens, fields narrows). Two equivalent forms:

import { createQueryApi, listQueryOptions } from '@haddowg/json-api-query'

// Bound API — the cleanest per-type call shape.
const reads = createQueryApi(client as unknown as ReadClient)
const listOpts = reads.albums.list({ include: ['artist'] })
const getOpts = reads.albums.get('1')
const relOpts = reads.albums.relationship('1', 'tracks') // linkage
const relatedOpts = reads.albums.related('1', 'tracks') // related collection

// Standalone factories — equivalent, with `client`/`type` passed explicitly.
const listOpts2 = listQueryOptions(client as unknown as ReadClient, 'albums', {
  include: ['artist'],
})

// Pass to your framework's useQuery, or fetch directly:
const albums = await queryClient.fetchQuery(listOpts)

The standalone factories are listQueryOptions, getQueryOptions, relationshipQueryOptions, relatedQueryOptions.

The query-key factory

Keys are stable, hierarchical readonly tuples — [type, operation, id?, rel?, params?]. The hierarchy is the contract targeted invalidation leans on (TanStack matches by prefix): [type] invalidates a whole type, [type, operation] an operation's subtree, [type, 'fetchOne', id] a single resource. Params ride the last segment as a normalised object, so two semantically-equal queries (keys reordered, equal values) share one key.

import { keyFor, operationKey, resourceKey, typeKey } from '@haddowg/json-api-query'

keyFor({ type: 'albums', operation: 'fetchOne', id: '1' }) // ['albums', 'fetchOne', '1']
typeKey('albums') // ['albums']
operationKey('albums', 'fetchMany') // ['albums', 'fetchMany']
resourceKey('albums', '1') // ['albums', 'fetchOne', '1']

queryClient.invalidateQueries({ queryKey: typeKey('albums') }) // every albums read

Also exported: relationKey, normalizeParams.

A singleton type's keys leave out the id (['inboxes', 'fetchOne']). Its factories take undefined for the id, which the types allow only for a singleton, and the bound API drops the argument: reads.inboxes.get(), writes.inboxes.update(), whose variables carry the resource's id for the request body.

Normalization (type:id write-through patching)

TanStack keeps denormalized results; this package indexes every resource (data + included) by type:id and, on a change, patches every cached query holding that type:id in place — "edit once, updates everywhere". Patching replaces a node's attributes (the descriptor knows attributes vs relations) while preserving edge-local $pivot / $edge. Each touched query then gets a new root reference over the same value, so components observing it re-render. The read factories set structuralSharing: false, since structural sharing would rebuild a refetched value as plain arrays and objects without its $page, $next() or $self; set it on any query you build yourself.

installNormalization auto-runs the patch on every successful query/mutation:

import { installNormalization } from '@haddowg/json-api-query'
import { resourceMap } from './api/music.gen'
import { QueryClient } from '@tanstack/query-core'

const queryClient = new QueryClient()
const teardown = installNormalization(queryClient, resourceMap)
// … later: teardown() removes the subscriptions.

One descriptor per QueryClient. The patch matches by type:id alone, so two descriptors sharing a QueryClient would cross-contaminate attributes. Installing a different descriptor on the same QueryClient throws. Give each typed client/server its own QueryClient.

Prefer explicit control? Skip the install and call normalize(queryClient, result, resourceMap) from an option factory's onSuccess — same write-through patch.

Writes — mutation option factories

Each returns a MutationOptions (mutationFn + the lifecycle callbacks the binding wires for normalization / invalidation / optimism), structurally compatible with query-core. The patch-vs-invalidate split:

  • an update (or a relationship set / replace) only changes a node's attributes/linkage → on success it patches via normalize (no refetch);
  • a create / delete changes collection membership → on settle it invalidates the relevant list / relationship subtrees so they refetch.
import { createMutationApi } from '@haddowg/json-api-query'

const writes = createMutationApi(queryClient, client as unknown as WriteClient, resourceMap)

// Create — invalidates the type's lists on settle; normalizes the new resource on success.
const createOpts = writes.albums.create()

// Update — patches across the cache on success. `{ optimistic: true }` pre-applies the patch's
// attributes through the normalized patch and rolls back on error.
const updateOpts = writes.albums.id('1').update({ optimistic: true })

// Delete — invalidates the type's lists + the resource's own reads.
const deleteOpts = writes.albums.id('1').delete()

// Relationship mutations — invalidate the parent's relation reads (never the type's lists).
const addOpts = writes.albums.id('1').rel('tracks').add()
const setOpts = writes.albums.id('1').rel('artist').set()

The variables a mutation takes mirror the client: create() takes the flat create input, update() the patch, add/remove/replace() the linkage refs, set() a ref or null.

The standalone factories are createMutationOptions, updateMutationOptions, deleteMutationOptions, addRelationshipMutationOptions, removeRelationshipMutationOptions, replaceRelationshipMutationOptions, setRelationshipMutationOptions, and a thin atomicMutationOptions passthrough.

Worked example (query-core directly)

const reads = createQueryApi(client as unknown as ReadClient)
const writes = createMutationApi(queryClient, client as unknown as WriteClient, resourceMap)

const listOpts = reads.albums.list()
const getOpts = reads.albums.get('1')
await queryClient.fetchQuery(listOpts)
await queryClient.fetchQuery(getOpts)

const updateOpts = writes.albums.id('1').update()
await queryClient
  .getMutationCache()
  .build(queryClient, updateOpts as never)
  .execute({ title: 'Fresh title' })

// Both the cached list AND the cached get now reflect the fresh title — patched by `type:id`,
// not refetched.
queryClient.getQueryData(listOpts.queryKey)
queryClient.getQueryData(getOpts.queryKey)

License

MIT

版本与发布记录

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

版本发布日期距今
1.7.2latest2026/11/17今天
1.7.12026/11/171 天前
1.7.02026/11/161 天前
1.6.02026/11/134 天前
1.5.02026/11/135 天前
1.4.22026/11/125 天前

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

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

TanStack Query bindings for the JSON:API client: option/key factories + type:id cache normalization.

如何安装 @haddowg/json-api-query?

在项目目录运行 npm install @haddowg/json-api-query,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@tanstack/query-core(^5.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@haddowg/json-api-query 支持 TypeScript 吗?

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

@haddowg/json-api-query 支持 ESM 还是 CommonJS?

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

@haddowg/json-api-query 需要什么版本的 Node.js?

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

@haddowg/json-api-query 可以商用吗?

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

@haddowg/json-api-query 的下载量有多少?

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

@haddowg/json-api-query 还在维护吗?

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