data-client-rest
/data-client-rest
Definiuje komunikację aplikacji z API przez @data-client/rest, w tym kształt zwracanych danych, wysyłanie żądań, zapisywanie, aktualizację i odświeżanie danych z użyciem resource, RestEndpoint i paginacji.
- Autor
- reactive ↗
- Repozytorium
- data-client ↗
- Licencja
- Apache-2.0
- Ostatnia zmiana repozytorium
- 27.10.2026
Ocena i bezpieczeństwo
- Pliki w paczce
- 42
- Skrypty
- 1
- Komentarze HTML
- 0
- Adresy URL w SKILL.md
- 13
Brak sygnałów. Repozytorium zmienione 27.10.2026, bez odwołań do wycofanych modeli i API.
Apache-2.0, otwarta: można używać i zmieniać, z zachowaniem licencji i informacji o zmianach.
- 1 skrypt w paczce. Przejrzyj je przed instalacją, bo Claude może je uruchomić.
Skrypty: references/RestEndpoint.js
Co robi i kiedy
Definiuje komunikację aplikacji z API przez @data-client/rest, w tym kształt zwracanych danych, wysyłanie żądań, zapisywanie, aktualizację i odświeżanie danych z użyciem resource, RestEndpoint i paginacji.
Oryginalny opis (EN)
Define how the app talks to its API with @data-client/rest, including the shape of the data each call returns. Use it when adding or changing any API call or its data, changing how requests are sent or responses are read, or deciding how fetched data is stored, updated and kept fresh. Covers resource, RestEndpoint and pagination.
Jak działa
- 1. Defining Schemas
- 2. Resources (resource())
- 3. Custom [RestEndpoint](references/RestEndpoint.md) patterns
- 4. Extending Resources
- 5. Best Practices & Notes
- 6. Common Mistakes to Avoid
Podgląd SKILL.md
---
name: data-client-rest
description: Define how the app talks to its API with @data-client/rest, including the shape of the data each call returns. Use it when adding or changing any API call or its data, changing how requests are sent or responses are read, or deciding how fetched data is stored, updated and kept fresh. Covers resource, RestEndpoint and pagination.
license: Apache 2.0
---
# Guide: Using `@data-client/rest` for Resource Modeling
This project uses [@data-client/rest](https://dataclient.io/rest) to define, fetch, normalize, and update RESTful resources and entities in React/TypeScript apps with type safety and automatic cache management.
**Always follow these patterns when generating code that interacts with remote APIs.**
---
## 1. Defining Schemas
Every `resource()` and `RestEndpoint` takes a `schema` that normalizes its response into the shared cache. Apply the
skill "data-client-schema" before defining or changing one: Entity, Collection, Union and Query patterns and references
live there, not here.
## 2. Resources (`resource()`)
- [resource()](references/resource.md) creates a collection of [RestEndpoints](references/RestEndpoint.md) for CRUD operations on a common object
- Required fields:
- `path`: path‑to‑regexp template (typed!)
- `schema`: Declarative data shape for a **single** item (typically Entity or Union)
- Optional:
- `urlPrefix`: Host root, if not `/`
- `searchParams`: Type for query parameters (TS generic) in MyResource.getList
- `paginationField`: Add MyResource.getList.getPage for pagination
- `optimistic`: Boolean, when true all mutations will update optimistically, improving performance
- `body`: Type for body parameter to MyResource.getList.push, MyResource.getList.unshift, MyResource.update, MyResource.partialUpdate
```ts
import { Entity, resource } from '@data-client/rest';
import { User } from './User';
export class Todo extends Entity {
id = 0;
user = User.fromJS();
title = '';
completed = false;
createdAt = new Date();
static key = 'Todo';
static schema = {
user: User,
createdAt: (iso: string) => new Date(iso),
}
}
export const TodoResource = resource({
urlPrefix: 'https://jsonplaceholder.typicode.com',
path: '/todos/:id',
schema: Todo,
searchParams: {} as { userId?: string | number } | undefined,
paginationField: 'page',
nonFilterArgumentKeys: ['orderBy'],
optimistic: true,
});
```
### Usage
#### [Rendering](references/data-dependency.md)
```ts
// GET https://jsonplaceholder.typicode.com/todos/5
const todo = useSuspense(TodoResource.get, { id: 5 });
// GET https://jsonplaceholder.typicode.com/todos
const todoList = useSuspense(TodoResource.getList);
// GET https://jsonplaceholder.typicode.com/todos?userId=1
const todoListByUser = useSuspense(TodoResource.getList, { userId: 1 });
```
#### [Mutations](references/mutations.md)
```ts
const ctrl = useController();
// PUT https://jsonplaceholder.typicode.com/todos/5
const updateTodo = todo => ctrl.fetch(TodoResource.update, { id }, todo);
// PATCH https://jsonplaceholder.typicode.com/todos/5
const partialUpdateTodo = todo =>
ctrl.fetch(TodoResource.partialUpdate, { id }, todo);
// POST https://jsonplaceholder.typicode.com/todos
const addTodoToStart = todo =>
ctrl.fetch(TodoResource.getList.unshift, todo);
// POST https://jsonplaceholder.typicode.com/todos?userId=1
const addTodoToEnd = todo => ctrl.fetch(TodoResource.getList.push, { userId: 1 }, todo);
// PATCH https://jsonplaceholder.typicode.com/todos/5
const toggleStatus = (completed: boolean) => ctrl.fetch(TodoResource.getList.move, { id }, { completed });
// DELETE https://jsonplaceholder.typicode.com/todos/5
const deleteTodo = id => ctrl.fetch(TodoResource.delete, { id });
// GET https://jsonplaceholder.typicode.com/todos?userId=1&page=2
const getNextPage = (page) => ctrl.fetch(TodoResource.getList.getPage, { userId: 1, page })
```
For more detailed usage, apply the skill "data-client-react" or "data-client-vue".
---
## 3. Custom [RestEndpoint](references/RestEndpoint.md) patterns
```ts
/** Stand‑alone endpoint with custom typing */
export const getTicker = new RestEndpoint({
urlPrefix: 'https://api.exchange.coinbase.com',
path: '/products/:product_id/ticker',
schema: Ticker,
pollFrequency: 2000,
});
```
`pollFrequency` polls only while subscribed (`useLive`/`useSubscription`). Subscribers to the same
endpoint and args share one poll at the fastest frequency, so a faster `.extend({ pollFrequency })` on
one view speeds up the others too.
**Typing tips**
- `path` path‑to‑regexp template for 1st arg
- `method` ≠ `GET` ⇒ 2nd arg = body (unless `body: undefined`)
- Provide `searchParams` / `body` _values_ purely for **type inference**
- Use `RestGenerics` when inheriting from `RestEndpoint`
### `getOptimisticResponse()`
```ts
getOptimisticResponse(snap, { id }) {
const article = snap.get(Article, { id });
if (!article) throw snap.abort;
return {
id,
votes: article.votes + 1,
};
}
```
---
### RestEndpoint lifecycle overrides
`fetch()` runs `fetchResponse(url(), getRequestInit())` → `parseResponse()` → `process()`. Override the
step that owns the change, never `fetch` itself (that replaces the whole lifecycle):
| To change | Override |
|---|---|
| Headers (auth) | `getHeaders(headers)` |
| Other request options or body encoding | `getRequestInit(body)` |
| Query string format | `searchToString(searchParams)` |
| 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)` |
---
## 4. **Extending Resources**
Use `.extend()` to add or override endpoints.
```typescript
export const IssueResource = resource({
// ...base config...
}).extend((Base) => ({
search: Base.getList.extend({
path: '/search/issues',
// ...custom schema or params...
}),
}));
```
---
## 5. Best Practices & Notes
- When asked to browse or navigate to a web address, actual visit the address
- Prefer `RestEndpoint` over `resource()` for defining single endpoints or when mutation endpoints don't exist
- For blob/file downloads and other non-JSON responses, see [network-transform: file download](references/network-transform.md#file-download).
## 6. Common Mistakes to Avoid
- Don't use `resource()` when mutation endpoints are not used or needed
# References
Vue projects: read `<name>.vue.md` instead of `<name>.md` when it exists.
For detailed API documentation, see the [references](references/) directory:
- [resource](references/resource.md) - Create CRUD endpoints
- [RestEndpoint](references/RestEndpoint.md);[_EndpointLifecycle.md](references/_EndpointLifecycle.md);[RestEndpoint.js](references/RestEndpoint.js) - Single REST endpoint
- Entity, Collection and other schemas: skill "data-client-schema"
- [Fixtures](references/Fixtures.md) - Mock data for testing
- [data-dependency](references/data-dependency.md);[_useLive.md](references/_useLive.md);[_AsyncBoundary.md](references/_AsyncBoundary.md) - Rendering guide
- [mutations](references/mutations.md);[_useLoading.md](references/_useLoading.md);[_VoteDemo.md](references/_VoteDemo.md) - Mutations guide
**Guides** (refer when user asks about these topics):
- [auth](references/auth.md) - Authentication headers, tokens, login/logout flows
- [pagination](references/pagination.md);[_pagination.md](references/_pagination.md) - Cursor/offset pagination, infinite scroll
- [optimistic-updates](references/optimistic-updates.md);[_optimisticTransform.md](references/_optimisticTransform.md) - Instant UI feedback before server response
- [network-transform](references/network-transform.md) - Transform responses, handle non-standard APIs
**Concepts** (refer when user asks about these topics):
- [expiry-policy](references/expiry-policy.md) - Cache invalidation, stale data, dataExpiryLength, errorExpiryLength
- [error-policy](references/error-policy.md) - Error handling, retry behavior, soft vs hard errors
**ALWAYS follow these patterns and refer to the official docs for edge cases. Prioritize code generation that is idiomatic, type-safe, and leverages automatic normalization/caching via schema definitions.**
Pliki w paczce (42)
- SKILL.md 8 KB
- references.json 1 KB
- evals/evals.json 1 KB
- references/Fixtures.md 6 KB
- references/Fixtures.vue.md 6 KB
- references/RestEndpoint.js 10 KB
- references/RestEndpoint.md 43 KB
- references/RestEndpoint.vue.md 44 KB
- references/_AsyncBoundary.md 2 KB
- references/_AsyncBoundary.vue.md 1 KB
- references/_EndpointLifecycle.md 6 KB
- references/_EndpointLifecycle.vue.md 7 KB
- references/_VoteDemo.md 3 KB
- references/_VoteDemo.vue.md 3 KB
- references/_optimisticTransform.md 2 KB
- references/_optimisticTransform.vue.md 2 KB
- references/_pagination.md 2 KB
- references/_pagination.vue.md 2 KB
- references/_useLive.md 1 KB
- references/_useLive.vue.md 1 KB
- references/_useLoading.md 3 KB
- references/_useLoading.vue.md 3 KB
- references/auth.md 9 KB
- references/auth.vue.md 10 KB
- references/data-dependency.md 12 KB
- references/data-dependency.vue.md 10 KB
- references/error-policy.md 4 KB
- references/error-policy.vue.md 4 KB
- references/expiry-policy.md 15 KB
- references/expiry-policy.vue.md 14 KB
- references/hookifyResource.md 6 KB
- references/hookifyResource.vue.md 6 KB
- references/mutations.md 9 KB
- references/mutations.vue.md 10 KB
- references/network-transform.md 11 KB
- references/network-transform.vue.md 11 KB
- references/optimistic-updates.md 12 KB
- references/optimistic-updates.vue.md 12 KB
- references/pagination.md 10 KB
- references/pagination.vue.md 10 KB
- references/resource.md 26 KB
- references/resource.vue.md 26 KB
Wersje
W bazie nie ma innych skilli o nazwie data-client-rest.
Migawka bazy z 13.11.2026 · wersja paczki f23b1a9fd8df (skrót SHA-256 całej paczki)
Pobrania w ostatnich 30 dniach: 0 · ranking
Zgłoś problem z tym skillem: szkodliwa treść, błędny opis albo prośba autora o usunięcie.
Podobne skille
- 100data-client-rest-setup
Konfiguruje i migruje projekt do @data-client/rest dla API REST: wykrywa istniejące wzorce HTTP (axios, fetch, ky, superagent, got) i tworzy własną bazową klasę RestEndpoint. - 100data-client-schema
Modeluje dane aplikacji schematami @data-client, które normalizują odpowiedzi do jednej współdzielonej pamięci podręcznej: Entity, GQLEntity, Collection, Union i Query. - 100api-design
Projektuje lub przegląda REST API: nazwy zasobów, kody statusu, stronicowanie, filtrowanie, błędy, wersjonowanie i limity. - 95api-design
Opisuje wzorce projektowania API REST: nazwy zasobów, kody statusu, stronicowanie, filtrowanie, błędy i wersjonowanie. - 95api-design
Opisuje wzorce projektowania REST API: nazwy zasobów, kody statusu, paginację, filtrowanie, odpowiedzi błędów, wersjonowanie i rate limiting dla API produkcyjnych. - 95api-design
Opisuje wzorce projektowania REST API: nazwy zasobów, kody statusu, paginację, filtrowanie, odpowiedzi błędów, wersjonowanie i rate limiting dla API produkcyjnych.