diff --git a/.agents/skills/data-client-rest-setup/SKILL.md b/.agents/skills/data-client-rest-setup/SKILL.md index cacc2adc9b03..420928cb9b57 100644 --- a/.agents/skills/data-client-rest-setup/SKILL.md +++ b/.agents/skills/data-client-rest-setup/SKILL.md @@ -72,7 +72,7 @@ Override only what the app does today: | Auth, CSRF or other headers (may be `async`, e.g. token refresh) | `getHeaders(headers)` | | Auth token from React context (Okta, Auth0) | [`hookifyResource()`](references/hookifyResource.md); a base class can't read context | | Cookies (axios `withCredentials`), other `RequestInit` | `async getRequestInit(body)` returning `{ ...(await super.getRequestInit(body)), credentials: 'include' }`. Without `await`, the spread drops `method`, `body` and headers, so every mutation is sent as a GET | -| A response interceptor reshapes the body without losing data: unwraps a `{ "data": ... }` with nothing beside it, converts key case | `async parseResponse(response)`, e.g. `return (await super.parseResponse(response))?.data` (null for a 204); `process()` would miss `resource().delete`. Fields the app reads, like `meta`, stay in the endpoint's schema | +| A response interceptor reshapes the body without losing data: unwraps a `{ "data": ... }` with nothing beside it, converts key case | `process(value)`, e.g. `return value?.data` (null for a 204). Fields the app reads, like `meta`, stay in the endpoint's schema | | Date fields | Not `process()`: the Entity's `static schema`, e.g. `createdAt: Temporal.Instant.from` (skill "data-client-schema") | | Status handling, like a 401 redirect | `async fetchResponse(input, init)`: `super.fetchResponse()` throws a `NetworkError` for any non-2xx status, so wrap it in `try`, check `error.status` in `catch`, and rethrow ([Server error messages](references/axios-migration.md#server-error-messages) shows it) | | Arrays or nested objects in the query | `searchToString(searchParams)`, e.g. `qs.stringify(searchParams, { arrayFormat: 'brackets' })` | diff --git a/.agents/skills/data-client-rest-setup/references/axios-migration.md b/.agents/skills/data-client-rest-setup/references/axios-migration.md index ec5d0a690f14..d3555fa0dd03 100644 --- a/.agents/skills/data-client-rest-setup/references/axios-migration.md +++ b/.agents/skills/data-client-rest-setup/references/axios-migration.md @@ -166,8 +166,7 @@ export default class ApiEndpoint< ``` Response interceptors that change the body, such as unwrapping `{ data }` or converting `snake_case` keys, go in -[`parseResponse()`](./RestEndpoint.md#parseResponse); see [snakes to camels](https://dataclient.io/rest/guides/network-transform#snakes-to-camels). -A base class's `process()` would miss `resource().delete`, which sets its own. +[`process()`](./RestEndpoint.md#process); see [snakes to camels](https://dataclient.io/rest/guides/network-transform#snakes-to-camels). When a response interceptor returned `response.data`, a caller's `.data` read a field of the body, not axios's response, so keep it. The codemod marks these calls when the interceptor is in the same file; if a global @@ -497,7 +496,7 @@ npm uninstall axios | `interceptors.request` | [`getHeaders()`](./RestEndpoint.md#getHeaders) / [`getRequestInit()`](./RestEndpoint.md#getRequestInit) | | `interceptors.response` | [`parseResponse()`](./RestEndpoint.md#parseResponse) / [`process()`](./RestEndpoint.md#process) | | `transformRequest` | [`getRequestInit()`](./RestEndpoint.md#getRequestInit) | -| `transformResponse` | [`parseResponse()`](./RestEndpoint.md#parseResponse) | +| `transformResponse` | [`process()`](./RestEndpoint.md#process) | | `isAxiosError` / `error.response` | [`NetworkError`](#error-handling) with `.status` and `.response` | | `cancelToken` / `signal` | [`signal`](#cancellation) | | `timeout` | [`AbortSignal.timeout()`](#timeout) in `getRequestInit()` | diff --git a/.agents/skills/data-client-rest-setup/references/axios-migration.vue.md b/.agents/skills/data-client-rest-setup/references/axios-migration.vue.md index ed76b288d216..1004b8d52634 100644 --- a/.agents/skills/data-client-rest-setup/references/axios-migration.vue.md +++ b/.agents/skills/data-client-rest-setup/references/axios-migration.vue.md @@ -166,8 +166,7 @@ export default class ApiEndpoint< ``` Response interceptors that change the body, such as unwrapping `{ data }` or converting `snake_case` keys, go in -[`parseResponse()`](./RestEndpoint.vue.md#parseResponse); see [snakes to camels](https://dataclient.io/rest/guides/network-transform#snakes-to-camels). -A base class's `process()` would miss `resource().delete`, which sets its own. +[`process()`](./RestEndpoint.vue.md#process); see [snakes to camels](https://dataclient.io/rest/guides/network-transform#snakes-to-camels). When a response interceptor returned `response.data`, a caller's `.data` read a field of the body, not axios's response, so keep it. The codemod marks these calls when the interceptor is in the same file; if a global @@ -497,7 +496,7 @@ npm uninstall axios | `interceptors.request` | [`getHeaders()`](./RestEndpoint.vue.md#getHeaders) / [`getRequestInit()`](./RestEndpoint.vue.md#getRequestInit) | | `interceptors.response` | [`parseResponse()`](./RestEndpoint.vue.md#parseResponse) / [`process()`](./RestEndpoint.vue.md#process) | | `transformRequest` | [`getRequestInit()`](./RestEndpoint.vue.md#getRequestInit) | -| `transformResponse` | [`parseResponse()`](./RestEndpoint.vue.md#parseResponse) | +| `transformResponse` | [`process()`](./RestEndpoint.vue.md#process) | | `isAxiosError` / `error.response` | [`NetworkError`](#error-handling) with `.status` and `.response` | | `cancelToken` / `signal` | [`signal`](#cancellation) | | `timeout` | [`AbortSignal.timeout()`](#timeout) in `getRequestInit()` | diff --git a/.agents/skills/data-client-rest-setup/references/got-migration.md b/.agents/skills/data-client-rest-setup/references/got-migration.md index 86a98082063d..3da3adb163cb 100644 --- a/.agents/skills/data-client-rest-setup/references/got-migration.md +++ b/.agents/skills/data-client-rest-setup/references/got-migration.md @@ -43,7 +43,7 @@ export const getUsers = new RestEndpoint({ | `headers` option | `getHeaders()` | | `searchParams` | `searchParams` type (same concept, different runtime) | | `hooks.beforeRequest` | `getHeaders()` or `getRequestInit()` | -| `hooks.afterResponse` | `parseResponse()` in the base class (`resource().delete` replaces a base `process()`) | +| `hooks.afterResponse` | `process()` in the base class | | `hooks.beforeError` | `fetchResponse()` override | | `.json()` | Automatic — RestEndpoint parses JSON by default | | `retry` (got retries by default) | Delete it: Data Client has no retry loop, and a failed request is fetched again when a component next needs it after `errorExpiryLength` (default 1 second). Tell the user that automatic retries are dropped | diff --git a/.agents/skills/data-client-rest-setup/references/ky-migration.md b/.agents/skills/data-client-rest-setup/references/ky-migration.md index 44e193fb0e15..0f2cd81f7cab 100644 --- a/.agents/skills/data-client-rest-setup/references/ky-migration.md +++ b/.agents/skills/data-client-rest-setup/references/ky-migration.md @@ -54,7 +54,7 @@ export const getUsers = new ApiEndpoint({ | `prefixUrl` | `urlPrefix` | | `headers` option | `getHeaders()` | | `hooks.beforeRequest` | `getHeaders()` or `getRequestInit()` | -| `hooks.afterResponse` | `parseResponse()` in the base class (`resource().delete` replaces a base `process()`) | +| `hooks.afterResponse` | `process()` in the base class | | `hooks.beforeError` | `fetchResponse()` override | | `ky.create()` shared options | Base class overrides | | `.json()` | Automatic — RestEndpoint parses JSON by default | diff --git a/.agents/skills/data-client-rest-setup/references/resource.md b/.agents/skills/data-client-rest-setup/references/resource.md index 497d48c38f26..d8a656ab7990 100644 --- a/.agents/skills/data-client-rest-setup/references/resource.md +++ b/.agents/skills/data-client-rest-setup/references/resource.md @@ -636,13 +636,15 @@ import { PostResource } from './Resource'; PostResource.delete({ group: 'react', id: '1' }); ``` -| Field | Value | -| :-----: | -------------------------------------------------------------------------------------------- | -| method | 'DELETE' | -| path | [path](#path) | -| schema | [new Invalidate(schema)](https://dataclient.io/rest/api/Invalidate) | +| Field | Value | +| :-----: | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| method | 'DELETE' | +| path | [path](#path) | +| schema | [new Invalidate(schema)](https://dataclient.io/rest/api/Invalidate) | | process | ```ts (value, params) { + // the resource's or Endpoint class's process() + value = value && Object.keys(value).length && super.process(value, params); return value && Object.keys(value).length ? value : params; }, ``` | diff --git a/.agents/skills/data-client-rest-setup/references/resource.vue.md b/.agents/skills/data-client-rest-setup/references/resource.vue.md index f911ba1475ab..ffb1dad83787 100644 --- a/.agents/skills/data-client-rest-setup/references/resource.vue.md +++ b/.agents/skills/data-client-rest-setup/references/resource.vue.md @@ -636,13 +636,15 @@ import { PostResource } from './Resource'; PostResource.delete({ group: 'react', id: '1' }); ``` -| Field | Value | -| :-----: | -------------------------------------------------------------------------------------------- | -| method | 'DELETE' | -| path | [path](#path) | -| schema | [new Invalidate(schema)](https://dataclient.io/rest/api/Invalidate) | +| Field | Value | +| :-----: | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| method | 'DELETE' | +| path | [path](#path) | +| schema | [new Invalidate(schema)](https://dataclient.io/rest/api/Invalidate) | | process | ```ts (value, params) { + // the resource's or Endpoint class's process() + value = value && Object.keys(value).length && super.process(value, params); return value && Object.keys(value).length ? value : params; }, ``` | diff --git a/.agents/skills/data-client-rest/SKILL.md b/.agents/skills/data-client-rest/SKILL.md index 110f73dafbbb..981e867b78cd 100644 --- a/.agents/skills/data-client-rest/SKILL.md +++ b/.agents/skills/data-client-rest/SKILL.md @@ -153,6 +153,7 @@ step that owns the change, never `fetch` itself (that replaces the whole lifecyc | The network call (retries, another client) | `fetchResponse(input, init)` | | Non-JSON responses | `content` option (`'blob'`, `'text'`, …), else `parseResponse(response)` | | Shape of the parsed data | `process(value, ...args)` | +| One Entity's fields, wherever it appears | `Entity.process()` (skill "data-client-schema") | --- @@ -214,7 +215,7 @@ Each guide holds working code. Read the matching section before writing code. | The next-page token is in a response header | "Tokens in HTTP Headers" in [pagination](references/pagination.md) | `parseResponse()` adds the header to the body | | The UI changes before the server answers | [optimistic-updates](references/optimistic-updates.md);[_optimisticTransform.md](references/_optimisticTransform.md) | `optimistic: true` on a resource; `getOptimisticResponse()` on other endpoints | | Responses can arrive out of order | "Compensating for Server timing variations" in [optimistic-updates](references/optimistic-updates.md) | compare `updatedAt` in `Entity.shouldReorder()` | -| The API's shape differs from the app's (key case, field types, primary key, headers) | [network-transform](references/network-transform.md) | `process()` / `getRequestInit()` / `parseResponse()` on the endpoint; `Entity.schema` for field types | +| The API's shape differs from the app's (key case, field types, primary key, headers) | [network-transform](references/network-transform.md) | `process()` / `getRequestInit()` / `parseResponse()` on the endpoint; `Entity.process()` for one Entity's fields wherever it appears; `Entity.schema` for field types | | A response is not JSON | "File download" in [network-transform](references/network-transform.md#file-download) | `content: 'blob'` | | How long data stays fresh, and refreshing it on demand | [expiry-policy](references/expiry-policy.md) | `dataExpiryLength`, `invalidIfStale`; `ctrl.fetch()` / `ctrl.expireAll()`; `ctrl.invalidate()` | | What shows when a refetch fails | [error-policy](references/error-policy.md) | `errorPolicy()`: `'soft'` keeps the last data, `'hard'` replaces it with the error | diff --git a/.agents/skills/data-client-rest/references/network-transform.md b/.agents/skills/data-client-rest/references/network-transform.md index 184a7c45f8db..ec8c4b103c9e 100644 --- a/.agents/skills/data-client-rest/references/network-transform.md +++ b/.agents/skills/data-client-rest/references/network-transform.md @@ -4,7 +4,8 @@ Transform data in [RestEndpoint](./RestEndpoint.md) members: [process()](./RestEndpoint.md#process) for responses, [getRequestInit()](./RestEndpoint.md#getRequestInit) for request bodies, and -[parseResponse()](./RestEndpoint.md#parseResponse) for headers and raw bodies. +[parseResponse()](./RestEndpoint.md#parseResponse) for headers and raw bodies. To change one Entity's fields +wherever it appears, including lists and nested data, use [Entity.process()](https://dataclient.io/rest/api/Entity#process). > **Tip** > @@ -13,9 +14,7 @@ responses, [getRequestInit()](./RestEndpoint.md#getRequestInit) for request bodi ## Snakes to camels -Many APIs use `snake_case` keys. To use `camelCase` in TypeScript, transform the keys in both directions. A base class -converts responses in [parseResponse()](./RestEndpoint.md#parseResponse), not `process()`, because -[resource()](./resource.md)'s `delete` sets its own `process()`, which replaces the class's. +Many APIs use `snake_case` keys. To use `camelCase` in TypeScript, transform the keys in both directions. ```typescript title="CamelResource.ts" import { camelCase, snakeCase } from 'lodash'; @@ -41,8 +40,7 @@ class CamelEndpoint extends RestEndpoint { } return super.getRequestInit(body); } - async parseResponse(response) { - const value = await super.parseResponse(response); + process(value) { // a 204 response has no body return value && deeplyApplyKeyTransform(value, camelCase); } @@ -343,30 +341,46 @@ For `ArrayBuffer` responses (useful for processing binary data in-memory), use ## Name calling -To rename a key the API uses, map it in both directions. Your Entity and components then use only your name. +To rename a key the API uses, map it in both directions: the Entity's [process()](https://dataclient.io/rest/api/Entity#process) renames it +in every response that contains the Entity, including lists and nested data, and the endpoint's +[getRequestInit()](./RestEndpoint.md#getRequestInit) renames it back in request bodies. Components then use only +your name. + +```typescript title="Article.ts" +import { Entity, RestEndpoint, RestGenerics } from '@data-client/rest'; + +export class Article extends Entity { + id = ''; + carrotsUsed = 0; + + static process(value: any, parent: any, key: string, args: any[]) { + const processed = super.process(value, parent, key, args); + if ('carrotsUsedIsThisNameTooLong' in processed) { + processed.carrotsUsed = processed.carrotsUsedIsThisNameTooLong; + delete processed.carrotsUsedIsThisNameTooLong; + } + return processed; + } +} -```typescript title="ArticleResource.ts" -class RenamedEndpoint< +export class RenamedEndpoint< O extends RestGenerics = any, > extends RestEndpoint { - getRequestInit(body) { + getRequestInit(body: any) { if (body && 'carrotsUsed' in body) { - const newBody = { - ...body, - carrotsUsedIsThisNameTooLong: body.carrotsUsed, - }; - delete newBody.carrotsUsed; - return super.getRequestInit(newBody); + const { carrotsUsed, ...rest } = body; + return super.getRequestInit({ + ...rest, + carrotsUsedIsThisNameTooLong: carrotsUsed, + }); } return super.getRequestInit(body); } - process(value) { - if ('carrotsUsedIsThisNameTooLong' in value) { - // ok to mutate jsonResponse since we control it - value.carrotsUsed = value.carrotsUsedIsThisNameTooLong; - delete value.carrotsUsedIsThisNameTooLong; - } - return value; - } } + +export const updateArticle = new RenamedEndpoint({ + path: '/articles/:id', + method: 'PATCH', + schema: Article, +}); ``` diff --git a/.agents/skills/data-client-rest/references/network-transform.vue.md b/.agents/skills/data-client-rest/references/network-transform.vue.md index bef348cd6012..d03343bdaa41 100644 --- a/.agents/skills/data-client-rest/references/network-transform.vue.md +++ b/.agents/skills/data-client-rest/references/network-transform.vue.md @@ -4,7 +4,8 @@ Transform data in [RestEndpoint](./RestEndpoint.vue.md) members: [process()](./RestEndpoint.vue.md#process) for responses, [getRequestInit()](./RestEndpoint.vue.md#getRequestInit) for request bodies, and -[parseResponse()](./RestEndpoint.vue.md#parseResponse) for headers and raw bodies. +[parseResponse()](./RestEndpoint.vue.md#parseResponse) for headers and raw bodies. To change one Entity's fields +wherever it appears, including lists and nested data, use [Entity.process()](https://dataclient.io/rest/api/Entity#process). > **Tip** > @@ -13,9 +14,7 @@ responses, [getRequestInit()](./RestEndpoint.vue.md#getRequestInit) for request ## Snakes to camels -Many APIs use `snake_case` keys. To use `camelCase` in TypeScript, transform the keys in both directions. A base class -converts responses in [parseResponse()](./RestEndpoint.vue.md#parseResponse), not `process()`, because -[resource()](./resource.vue.md)'s `delete` sets its own `process()`, which replaces the class's. +Many APIs use `snake_case` keys. To use `camelCase` in TypeScript, transform the keys in both directions. ```typescript title="CamelResource.ts" import { camelCase, snakeCase } from 'lodash'; @@ -41,8 +40,7 @@ class CamelEndpoint extends RestEndpoint { } return super.getRequestInit(body); } - async parseResponse(response) { - const value = await super.parseResponse(response); + process(value) { // a 204 response has no body return value && deeplyApplyKeyTransform(value, camelCase); } @@ -345,30 +343,46 @@ For `ArrayBuffer` responses (useful for processing binary data in-memory), use ## Name calling -To rename a key the API uses, map it in both directions. Your Entity and components then use only your name. +To rename a key the API uses, map it in both directions: the Entity's [process()](https://dataclient.io/rest/api/Entity#process) renames it +in every response that contains the Entity, including lists and nested data, and the endpoint's +[getRequestInit()](./RestEndpoint.vue.md#getRequestInit) renames it back in request bodies. Components then use only +your name. + +```typescript title="Article.ts" +import { Entity, RestEndpoint, RestGenerics } from '@data-client/rest'; + +export class Article extends Entity { + id = ''; + carrotsUsed = 0; + + static process(value: any, parent: any, key: string, args: any[]) { + const processed = super.process(value, parent, key, args); + if ('carrotsUsedIsThisNameTooLong' in processed) { + processed.carrotsUsed = processed.carrotsUsedIsThisNameTooLong; + delete processed.carrotsUsedIsThisNameTooLong; + } + return processed; + } +} -```typescript title="ArticleResource.ts" -class RenamedEndpoint< +export class RenamedEndpoint< O extends RestGenerics = any, > extends RestEndpoint { - getRequestInit(body) { + getRequestInit(body: any) { if (body && 'carrotsUsed' in body) { - const newBody = { - ...body, - carrotsUsedIsThisNameTooLong: body.carrotsUsed, - }; - delete newBody.carrotsUsed; - return super.getRequestInit(newBody); + const { carrotsUsed, ...rest } = body; + return super.getRequestInit({ + ...rest, + carrotsUsedIsThisNameTooLong: carrotsUsed, + }); } return super.getRequestInit(body); } - process(value) { - if ('carrotsUsedIsThisNameTooLong' in value) { - // ok to mutate jsonResponse since we control it - value.carrotsUsed = value.carrotsUsedIsThisNameTooLong; - delete value.carrotsUsedIsThisNameTooLong; - } - return value; - } } + +export const updateArticle = new RenamedEndpoint({ + path: '/articles/:id', + method: 'PATCH', + schema: Article, +}); ``` diff --git a/.agents/skills/data-client-rest/references/resource.md b/.agents/skills/data-client-rest/references/resource.md index 241df1592c4f..c2f066c90d42 100644 --- a/.agents/skills/data-client-rest/references/resource.md +++ b/.agents/skills/data-client-rest/references/resource.md @@ -636,13 +636,15 @@ import { PostResource } from './Resource'; PostResource.delete({ group: 'react', id: '1' }); ``` -| Field | Value | -| :-----: | -------------------------------------------------------------------------------------------- | -| method | 'DELETE' | -| path | [path](#path) | -| schema | [new Invalidate(schema)](https://dataclient.io/rest/api/Invalidate) | +| Field | Value | +| :-----: | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| method | 'DELETE' | +| path | [path](#path) | +| schema | [new Invalidate(schema)](https://dataclient.io/rest/api/Invalidate) | | process | ```ts (value, params) { + // the resource's or Endpoint class's process() + value = value && Object.keys(value).length && super.process(value, params); return value && Object.keys(value).length ? value : params; }, ``` | diff --git a/.agents/skills/data-client-rest/references/resource.vue.md b/.agents/skills/data-client-rest/references/resource.vue.md index b3cbab79b26c..48efb6ade2e4 100644 --- a/.agents/skills/data-client-rest/references/resource.vue.md +++ b/.agents/skills/data-client-rest/references/resource.vue.md @@ -636,13 +636,15 @@ import { PostResource } from './Resource'; PostResource.delete({ group: 'react', id: '1' }); ``` -| Field | Value | -| :-----: | -------------------------------------------------------------------------------------------- | -| method | 'DELETE' | -| path | [path](#path) | -| schema | [new Invalidate(schema)](https://dataclient.io/rest/api/Invalidate) | +| Field | Value | +| :-----: | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| method | 'DELETE' | +| path | [path](#path) | +| schema | [new Invalidate(schema)](https://dataclient.io/rest/api/Invalidate) | | process | ```ts (value, params) { + // the resource's or Endpoint class's process() + value = value && Object.keys(value).length && super.process(value, params); return value && Object.keys(value).length ? value : params; }, ``` | diff --git a/.agents/skills/data-client-setup/references/data-client-rest-setup.md b/.agents/skills/data-client-setup/references/data-client-rest-setup.md index c4d22185007d..31c63f42dc60 100644 --- a/.agents/skills/data-client-setup/references/data-client-rest-setup.md +++ b/.agents/skills/data-client-setup/references/data-client-rest-setup.md @@ -68,7 +68,7 @@ Override only what the app does today: | Auth, CSRF or other headers (may be `async`, e.g. token refresh) | `getHeaders(headers)` | | Auth token from React context (Okta, Auth0) | [`hookifyResource()`](./data-client-rest-setup/references/hookifyResource.md); a base class can't read context | | Cookies (axios `withCredentials`), other `RequestInit` | `async getRequestInit(body)` returning `{ ...(await super.getRequestInit(body)), credentials: 'include' }`. Without `await`, the spread drops `method`, `body` and headers, so every mutation is sent as a GET | -| A response interceptor reshapes the body without losing data: unwraps a `{ "data": ... }` with nothing beside it, converts key case | `async parseResponse(response)`, e.g. `return (await super.parseResponse(response))?.data` (null for a 204); `process()` would miss `resource().delete`. Fields the app reads, like `meta`, stay in the endpoint's schema | +| A response interceptor reshapes the body without losing data: unwraps a `{ "data": ... }` with nothing beside it, converts key case | `process(value)`, e.g. `return value?.data` (null for a 204). Fields the app reads, like `meta`, stay in the endpoint's schema | | Date fields | Not `process()`: the Entity's `static schema`, e.g. `createdAt: Temporal.Instant.from` (skill "data-client-schema") | | Status handling, like a 401 redirect | `async fetchResponse(input, init)`: `super.fetchResponse()` throws a `NetworkError` for any non-2xx status, so wrap it in `try`, check `error.status` in `catch`, and rethrow ([Server error messages](./data-client-rest-setup/references/axios-migration.md#server-error-messages) shows it) | | Arrays or nested objects in the query | `searchToString(searchParams)`, e.g. `qs.stringify(searchParams, { arrayFormat: 'brackets' })` | diff --git a/.agents/skills/data-client-setup/references/data-client-rest-setup/references/axios-migration.md b/.agents/skills/data-client-setup/references/data-client-rest-setup/references/axios-migration.md index ec5d0a690f14..d3555fa0dd03 100644 --- a/.agents/skills/data-client-setup/references/data-client-rest-setup/references/axios-migration.md +++ b/.agents/skills/data-client-setup/references/data-client-rest-setup/references/axios-migration.md @@ -166,8 +166,7 @@ export default class ApiEndpoint< ``` Response interceptors that change the body, such as unwrapping `{ data }` or converting `snake_case` keys, go in -[`parseResponse()`](./RestEndpoint.md#parseResponse); see [snakes to camels](https://dataclient.io/rest/guides/network-transform#snakes-to-camels). -A base class's `process()` would miss `resource().delete`, which sets its own. +[`process()`](./RestEndpoint.md#process); see [snakes to camels](https://dataclient.io/rest/guides/network-transform#snakes-to-camels). When a response interceptor returned `response.data`, a caller's `.data` read a field of the body, not axios's response, so keep it. The codemod marks these calls when the interceptor is in the same file; if a global @@ -497,7 +496,7 @@ npm uninstall axios | `interceptors.request` | [`getHeaders()`](./RestEndpoint.md#getHeaders) / [`getRequestInit()`](./RestEndpoint.md#getRequestInit) | | `interceptors.response` | [`parseResponse()`](./RestEndpoint.md#parseResponse) / [`process()`](./RestEndpoint.md#process) | | `transformRequest` | [`getRequestInit()`](./RestEndpoint.md#getRequestInit) | -| `transformResponse` | [`parseResponse()`](./RestEndpoint.md#parseResponse) | +| `transformResponse` | [`process()`](./RestEndpoint.md#process) | | `isAxiosError` / `error.response` | [`NetworkError`](#error-handling) with `.status` and `.response` | | `cancelToken` / `signal` | [`signal`](#cancellation) | | `timeout` | [`AbortSignal.timeout()`](#timeout) in `getRequestInit()` | diff --git a/.agents/skills/data-client-setup/references/data-client-rest-setup/references/axios-migration.vue.md b/.agents/skills/data-client-setup/references/data-client-rest-setup/references/axios-migration.vue.md index ed76b288d216..1004b8d52634 100644 --- a/.agents/skills/data-client-setup/references/data-client-rest-setup/references/axios-migration.vue.md +++ b/.agents/skills/data-client-setup/references/data-client-rest-setup/references/axios-migration.vue.md @@ -166,8 +166,7 @@ export default class ApiEndpoint< ``` Response interceptors that change the body, such as unwrapping `{ data }` or converting `snake_case` keys, go in -[`parseResponse()`](./RestEndpoint.vue.md#parseResponse); see [snakes to camels](https://dataclient.io/rest/guides/network-transform#snakes-to-camels). -A base class's `process()` would miss `resource().delete`, which sets its own. +[`process()`](./RestEndpoint.vue.md#process); see [snakes to camels](https://dataclient.io/rest/guides/network-transform#snakes-to-camels). When a response interceptor returned `response.data`, a caller's `.data` read a field of the body, not axios's response, so keep it. The codemod marks these calls when the interceptor is in the same file; if a global @@ -497,7 +496,7 @@ npm uninstall axios | `interceptors.request` | [`getHeaders()`](./RestEndpoint.vue.md#getHeaders) / [`getRequestInit()`](./RestEndpoint.vue.md#getRequestInit) | | `interceptors.response` | [`parseResponse()`](./RestEndpoint.vue.md#parseResponse) / [`process()`](./RestEndpoint.vue.md#process) | | `transformRequest` | [`getRequestInit()`](./RestEndpoint.vue.md#getRequestInit) | -| `transformResponse` | [`parseResponse()`](./RestEndpoint.vue.md#parseResponse) | +| `transformResponse` | [`process()`](./RestEndpoint.vue.md#process) | | `isAxiosError` / `error.response` | [`NetworkError`](#error-handling) with `.status` and `.response` | | `cancelToken` / `signal` | [`signal`](#cancellation) | | `timeout` | [`AbortSignal.timeout()`](#timeout) in `getRequestInit()` | diff --git a/.agents/skills/data-client-setup/references/data-client-rest-setup/references/got-migration.md b/.agents/skills/data-client-setup/references/data-client-rest-setup/references/got-migration.md index d993d08944d9..c71c00b89058 100644 --- a/.agents/skills/data-client-setup/references/data-client-rest-setup/references/got-migration.md +++ b/.agents/skills/data-client-setup/references/data-client-rest-setup/references/got-migration.md @@ -45,7 +45,7 @@ export const getUsers = new RestEndpoint({ | `headers` option | `getHeaders()` | | `searchParams` | `searchParams` type (same concept, different runtime) | | `hooks.beforeRequest` | `getHeaders()` or `getRequestInit()` | -| `hooks.afterResponse` | `parseResponse()` in the base class (`resource().delete` replaces a base `process()`) | +| `hooks.afterResponse` | `process()` in the base class | | `hooks.beforeError` | `fetchResponse()` override | | `.json()` | Automatic — RestEndpoint parses JSON by default | | `retry` (got retries by default) | Delete it: Data Client has no retry loop, and a failed request is fetched again when a component next needs it after `errorExpiryLength` (default 1 second). Tell the user that automatic retries are dropped | diff --git a/.agents/skills/data-client-setup/references/data-client-rest-setup/references/ky-migration.md b/.agents/skills/data-client-setup/references/data-client-rest-setup/references/ky-migration.md index 8bcb193d8cd0..a356012e45e9 100644 --- a/.agents/skills/data-client-setup/references/data-client-rest-setup/references/ky-migration.md +++ b/.agents/skills/data-client-setup/references/data-client-rest-setup/references/ky-migration.md @@ -56,7 +56,7 @@ export const getUsers = new ApiEndpoint({ | `prefixUrl` | `urlPrefix` | | `headers` option | `getHeaders()` | | `hooks.beforeRequest` | `getHeaders()` or `getRequestInit()` | -| `hooks.afterResponse` | `parseResponse()` in the base class (`resource().delete` replaces a base `process()`) | +| `hooks.afterResponse` | `process()` in the base class | | `hooks.beforeError` | `fetchResponse()` override | | `ky.create()` shared options | Base class overrides | | `.json()` | Automatic — RestEndpoint parses JSON by default | diff --git a/.agents/skills/data-client-setup/references/data-client-rest-setup/references/resource.md b/.agents/skills/data-client-setup/references/data-client-rest-setup/references/resource.md index 497d48c38f26..d8a656ab7990 100644 --- a/.agents/skills/data-client-setup/references/data-client-rest-setup/references/resource.md +++ b/.agents/skills/data-client-setup/references/data-client-rest-setup/references/resource.md @@ -636,13 +636,15 @@ import { PostResource } from './Resource'; PostResource.delete({ group: 'react', id: '1' }); ``` -| Field | Value | -| :-----: | -------------------------------------------------------------------------------------------- | -| method | 'DELETE' | -| path | [path](#path) | -| schema | [new Invalidate(schema)](https://dataclient.io/rest/api/Invalidate) | +| Field | Value | +| :-----: | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| method | 'DELETE' | +| path | [path](#path) | +| schema | [new Invalidate(schema)](https://dataclient.io/rest/api/Invalidate) | | process | ```ts (value, params) { + // the resource's or Endpoint class's process() + value = value && Object.keys(value).length && super.process(value, params); return value && Object.keys(value).length ? value : params; }, ``` | diff --git a/.agents/skills/data-client-setup/references/data-client-rest-setup/references/resource.vue.md b/.agents/skills/data-client-setup/references/data-client-rest-setup/references/resource.vue.md index f911ba1475ab..ffb1dad83787 100644 --- a/.agents/skills/data-client-setup/references/data-client-rest-setup/references/resource.vue.md +++ b/.agents/skills/data-client-setup/references/data-client-rest-setup/references/resource.vue.md @@ -636,13 +636,15 @@ import { PostResource } from './Resource'; PostResource.delete({ group: 'react', id: '1' }); ``` -| Field | Value | -| :-----: | -------------------------------------------------------------------------------------------- | -| method | 'DELETE' | -| path | [path](#path) | -| schema | [new Invalidate(schema)](https://dataclient.io/rest/api/Invalidate) | +| Field | Value | +| :-----: | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| method | 'DELETE' | +| path | [path](#path) | +| schema | [new Invalidate(schema)](https://dataclient.io/rest/api/Invalidate) | | process | ```ts (value, params) { + // the resource's or Endpoint class's process() + value = value && Object.keys(value).length && super.process(value, params); return value && Object.keys(value).length ? value : params; }, ``` | diff --git a/.changeset/delete-base-process.md b/.changeset/delete-base-process.md new file mode 100644 index 000000000000..290af665ba32 --- /dev/null +++ b/.changeset/delete-base-process.md @@ -0,0 +1,23 @@ +--- +'@data-client/rest': patch +--- + +`resource().delete` runs the `Endpoint` class's `process()` (or the resource's `process` option) + +A `resource()` `delete` sets its own `process()`, which used to replace the one from the `Endpoint` class, so a base class that unwrapped an envelope or converted key case returned the raw body for `delete` only. `delete` now passes a non-empty body through that `process()` first. An empty body, or one that `process()` empties (like `{ "data": null }`), still becomes the params. + +```ts +class ApiEndpoint extends RestEndpoint { + process(value: any) { + return value?.data; + } +} + +const UserResource = resource({ + path: '/users/:id', + schema: User, + Endpoint: ApiEndpoint, +}); +// { "data": { "id": 5 } } -> { id: 5 }, like every other UserResource endpoint +await UserResource.delete({ id: 5 }); +``` diff --git a/docs/rest/api/_DeleteProcess.mdx b/docs/rest/api/_DeleteProcess.mdx index 0c591e7e287e..7485c307a77d 100644 --- a/docs/rest/api/_DeleteProcess.mdx +++ b/docs/rest/api/_DeleteProcess.mdx @@ -1,5 +1,7 @@ ```ts (value, params) { + // the resource's or Endpoint class's process() + value = value && Object.keys(value).length && super.process(value, params); return value && Object.keys(value).length ? value : params; }, -``` \ No newline at end of file +``` diff --git a/docs/rest/guides/axios-migration.md b/docs/rest/guides/axios-migration.md index daf3bb7c2442..b7ff7d1fe241 100644 --- a/docs/rest/guides/axios-migration.md +++ b/docs/rest/guides/axios-migration.md @@ -215,8 +215,7 @@ export default class ApiEndpoint< Response interceptors that change the body, such as unwrapping `{ data }` or converting `snake_case` keys, go in -[`parseResponse()`](../api/RestEndpoint.md#parseResponse); see [snakes to camels](./network-transform.md#snakes-to-camels). -A base class's `process()` would miss `resource().delete`, which sets its own. +[`process()`](../api/RestEndpoint.md#process); see [snakes to camels](./network-transform.md#snakes-to-camels). When a response interceptor returned `response.data`, a caller's `.data` read a field of the body, not axios's response, so keep it. The codemod marks these calls when the interceptor is in the same file; if a global @@ -557,7 +556,7 @@ npm uninstall axios | `interceptors.request` | [`getHeaders()`](../api/RestEndpoint.md#getHeaders) / [`getRequestInit()`](../api/RestEndpoint.md#getRequestInit) | | `interceptors.response` | [`parseResponse()`](../api/RestEndpoint.md#parseResponse) / [`process()`](../api/RestEndpoint.md#process) | | `transformRequest` | [`getRequestInit()`](../api/RestEndpoint.md#getRequestInit) | -| `transformResponse` | [`parseResponse()`](../api/RestEndpoint.md#parseResponse) | +| `transformResponse` | [`process()`](../api/RestEndpoint.md#process) | | `isAxiosError` / `error.response` | [`NetworkError`](#error-handling) with `.status` and `.response` | | `cancelToken` / `signal` | [`signal`](#cancellation) | | `timeout` | [`AbortSignal.timeout()`](#timeout) in `getRequestInit()` | diff --git a/docs/rest/guides/network-transform.md b/docs/rest/guides/network-transform.md index 1572088738e2..e7369cd9db85 100644 --- a/docs/rest/guides/network-transform.md +++ b/docs/rest/guides/network-transform.md @@ -7,7 +7,8 @@ import { RestEndpoint } from '@data-client/rest'; Transform data in [RestEndpoint](../api/RestEndpoint.md) members: [process()](../api/RestEndpoint.md#process) for responses, [getRequestInit()](../api/RestEndpoint.md#getRequestInit) for request bodies, and -[parseResponse()](../api/RestEndpoint.md#parseResponse) for headers and raw bodies. +[parseResponse()](../api/RestEndpoint.md#parseResponse) for headers and raw bodies. To change one Entity's fields +wherever it appears, including lists and nested data, use [Entity.process()](../api/Entity.md#process). :::tip @@ -18,9 +19,7 @@ for APIs you do not control. ## Snakes to camels -Many APIs use `snake_case` keys. To use `camelCase` in TypeScript, transform the keys in both directions. A base class -converts responses in [parseResponse()](../api/RestEndpoint.md#parseResponse), not `process()`, because -[resource()](../api/resource.md)'s `delete` sets its own `process()`, which replaces the class's. +Many APIs use `snake_case` keys. To use `camelCase` in TypeScript, transform the keys in both directions. ```typescript title="CamelResource.ts" import { camelCase, snakeCase } from 'lodash'; @@ -46,8 +45,7 @@ class CamelEndpoint extends RestEndpoint { } return super.getRequestInit(body); } - async parseResponse(response) { - const value = await super.parseResponse(response); + process(value) { // a 204 response has no body return value && deeplyApplyKeyTransform(value, camelCase); } @@ -471,30 +469,46 @@ For `ArrayBuffer` responses (useful for processing binary data in-memory), use ## Name calling -To rename a key the API uses, map it in both directions. Your Entity and components then use only your name. +To rename a key the API uses, map it in both directions: the Entity's [process()](../api/Entity.md#process) renames it +in every response that contains the Entity, including lists and nested data, and the endpoint's +[getRequestInit()](../api/RestEndpoint.md#getRequestInit) renames it back in request bodies. Components then use only +your name. + +```typescript title="Article.ts" +import { Entity, RestEndpoint, RestGenerics } from '@data-client/rest'; + +export class Article extends Entity { + id = ''; + carrotsUsed = 0; + + static process(value: any, parent: any, key: string, args: any[]) { + const processed = super.process(value, parent, key, args); + if ('carrotsUsedIsThisNameTooLong' in processed) { + processed.carrotsUsed = processed.carrotsUsedIsThisNameTooLong; + delete processed.carrotsUsedIsThisNameTooLong; + } + return processed; + } +} -```typescript title="ArticleResource.ts" -class RenamedEndpoint< +export class RenamedEndpoint< O extends RestGenerics = any, > extends RestEndpoint { - getRequestInit(body) { + getRequestInit(body: any) { if (body && 'carrotsUsed' in body) { - const newBody = { - ...body, - carrotsUsedIsThisNameTooLong: body.carrotsUsed, - }; - delete newBody.carrotsUsed; - return super.getRequestInit(newBody); + const { carrotsUsed, ...rest } = body; + return super.getRequestInit({ + ...rest, + carrotsUsedIsThisNameTooLong: carrotsUsed, + }); } return super.getRequestInit(body); } - process(value) { - if ('carrotsUsedIsThisNameTooLong' in value) { - // ok to mutate jsonResponse since we control it - value.carrotsUsed = value.carrotsUsedIsThisNameTooLong; - delete value.carrotsUsedIsThisNameTooLong; - } - return value; - } } + +export const updateArticle = new RenamedEndpoint({ + path: '/articles/:id', + method: 'PATCH', + schema: Article, +}); ``` diff --git a/packages/rest/src/__tests__/resource-construction.test.ts b/packages/rest/src/__tests__/resource-construction.test.ts index 041c79d3529a..4ca24f866ef9 100644 --- a/packages/rest/src/__tests__/resource-construction.test.ts +++ b/packages/rest/src/__tests__/resource-construction.test.ts @@ -560,6 +560,41 @@ describe('resource()', () => { ).toThrowErrorMatchingSnapshot(); }); + class UnwrapEndpoint extends RestEndpoint { + process(value: any, ..._args: any) { + return value.data; + } + } + const path = 'http\\://test.com/groups/:group/users/:id'; + it.each([ + [ + 'base class process()', + resource({ path, schema: User, Endpoint: UnwrapEndpoint }), + ], + [ + 'resource process option', + resource({ path, schema: User, process: (value: any) => value.data }), + ], + ])('delete runs the %s', async (_, EnvelopeResource) => { + mynock + .delete(`/groups/five/users/5`) + .reply(200, { data: { id: 5 }, meta: {} }) + .delete(`/groups/five/users/6`) + .reply(204) + .delete(`/groups/five/users/7`) + .reply(200, { data: null }); + await expect( + EnvelopeResource.delete({ group: 'five', id: '5' }), + ).resolves.toEqual({ id: 5 }); + // an empty body, or one process() empties, becomes the params + await expect( + EnvelopeResource.delete({ group: 'five', id: '6' }), + ).resolves.toEqual({ group: 'five', id: '6' }); + await expect( + EnvelopeResource.delete({ group: 'five', id: '7' }), + ).resolves.toEqual({ group: 'five', id: '7' }); + }); + it('UserResource.get should work', async () => { const { result, waitForNextUpdate } = renderDataClient(() => { return useSuspense(UserResource.get, { group: 'five', id: '5' }); diff --git a/packages/rest/src/resource.ts b/packages/rest/src/resource.ts index 7898a57bbb32..9a2fb2a27fce 100644 --- a/packages/rest/src/resource.ts +++ b/packages/rest/src/resource.ts @@ -144,7 +144,16 @@ This warning will not show in production.`, // a `body` in the resource's options is for its other mutations body: undefined, name: getName('delete'), + // runs the resource's or Endpoint class's process(); an empty result becomes params process(res: any, params: any) { + res = + res && + Object.keys(res).length && + (extraMutateOptions.process || Endpoint.prototype.process).call( + this, + res, + params, + ); return res && Object.keys(res).length ? res : params; }, getOptimisticResponse: optimistic ? (optimisticDelete as any) : undefined, diff --git a/website/blog/2026-11-17-v0.19-batch-set.md b/website/blog/2026-11-17-v0.19-batch-set.md index 7b68df089d15..95e8b41296d4 100644 --- a/website/blog/2026-11-17-v0.19-batch-set.md +++ b/website/blog/2026-11-17-v0.19-batch-set.md @@ -862,6 +862,7 @@ render(); ### Other REST changes {#rest-changes} - `rest` **Fix:** A `DELETE` endpoint that declares `body` sends it. Before, the request went out with no body and the last argument became URL params (`DELETE /posts?0=5&1=13`). If you call such an endpoint without a body, remove `body` or set `body: undefined` ([#4528](https://github.com/reactive/data-client/pull/4528)) +- `rest` **Fix:** [resource()](/rest/api/resource)'s `delete` runs your `Endpoint` class's [process()](/rest/api/RestEndpoint#process), or the resource's `process` option. Before, `delete` set its own `process()`, which replaced the base class's, so a base class that unwrapped `{ "data": ... }` or converted key case returned the raw body for `delete` only. An empty body, or one your `process()` empties, still becomes the params ([#4698](https://github.com/reactive/data-client/pull/4698)) ## Validation {#validation}