reactive/data-client / .agents/skills/data-client-schema
data-client-schema
VerifiedModel the app's data with @data-client schemas, which normalize responses into one shared cache so an update shows everywhere. Use it whenever an endpoint returning data is added or its response changes (resource, RestEndpoint, GraphQL, Endpoint), when the data's shape changes, when data from different endpoints must be joined or related, when deriving views from loaded data, or when one item looks different in two places. Covers Entity, GQLEntity, Collection, Union and Query.
references/schema.md
View on GitHub<!-- Generated by `yarn build:skills` from docs/rest/api/schema.md (react). Edit the source doc, not this file. -->
# Thinking in Schemas
Consider a typical blog post. The API response for a single post might look something like this:
```json
{
"id": "123",
"author": {
"id": "1",
"name": "Paul"
},
"title": "My awesome blog post",
"comments": [
{
"id": "324",
"createdAt": "2013-05-29T00:00:00-04:00",
"commenter": {
"id": "2",
"name": "Nicole"
}
},
{
"id": "544",
"createdAt": "2013-05-30T00:00:00-04:00",
"commenter": {
"id": "1",
"name": "Paul"
}
}
]
}
```
## Declarative definitions
We have two nested [entity](./Entity.md) types within our `article`: `users` and `comments`. Using various [schema](./Entity.md#schema), we can normalize all three entity types down:
```typescript
import { schema, Entity } from '@data-client/endpoint';
import { Temporal } from 'temporal-polyfill';
class User extends Entity {
id = '';
name = '';
}
class Comment extends Entity {
id = '';
createdAt = Temporal.Instant.fromEpochMilliseconds(0);
commenter = User.fromJS();
static schema = {
commenter: User,
createdAt: Temporal.Instant.from,
};
}
class Article extends Entity {
id = '';
title = '';
author = User.fromJS();
comments: Comment[] = [];
static schema = {
author: User,
comments: [Comment],
};
}
```
```javascript
import { schema, Entity } from '@data-client/endpoint';
import { Temporal } from 'temporal-polyfill';
class User extends Entity { }
class Comment extends Entity {
static schema = {
commenter: User,
createdAt: Temporal.Instant.from,
};
}
class Article extends Entity {
static schema = {
author: User,
comments: [Comment],
};
}
```
## Normalize
```js
import { normalize } from '@data-client/normalizr';
const args = [{ id: '123' }];
const normalizedData = normalize(Article, originalData, args);
```
Now, `normalizedData` will create a single serializable source of truth for all entities:
```js
{
result: "123",
entities: {
articles: {
"123": {
id: "123",
author: "1",
title: "My awesome blog post",
comments: [ "324", "544" ]
}
},
users: {
"1": { "id": "1", "name": "Paul" },
"2": { "id": "2", "name": "Nicole" }
},
comments: {
"324": {
id: "324",
createdAt: "2013-05-29T00:00:00-04:00",
commenter: "2"
},
"544": {
id: "544",
createdAt: "2013-05-30T00:00:00-04:00",
commenter: "1"
}
}
},
// contents excluded for brevity
indexes,
entitiesMeta,
}
```
## Denormalize
```js
import { denormalize } from '@data-client/normalizr';
const denormalizedData = denormalize(
Article,
normalizedData.result,
normalizedData.entities,
args,
);
```
Now, `denormalizedData` will instantiate the classes, ensuring all instances of the same member (like `Paul`) are referentially equal:
```js
Article {
id: '123',
title: 'My awesome blog post',
author: User { id: '1', name: 'Paul' },
comments: [
Comment {
id: '324',
createdAt: Instant [Temporal.Instant] {},
commenter: [User { id: '2', name: 'Nicole' }]
},
Comment {
id: '544',
createdAt: Instant [Temporal.Instant] {},
commenter: [User { id: '1', name: 'Paul' }]
}
]
}
```
### MemoCache
`MemoCache` is a singleton that can be used to maintain referential equality between calls as well
as potentially improved performance by 2000%. Its methods are memoized.
#### memo.denormalize
```js
import { MemoCache } from '@data-client/normalizr';
// you can construct a new memo anytime you want to reset the cache
const memo = new MemoCache();
const { data, paths } = memo.denormalize(
Article,
normalizedData.result,
normalizedData.entities,
args,
);
const { data: data2 } = memo.denormalize(
Article,
normalizedData.result,
normalizedData.entities,
args,
);
// referential equality maintained between calls
assert(data === data2);
```
`memo.denormalize()` is just like [denormalize()](#denormalize) above but includes `paths` as part of the return value. `paths`
is an Array of paths of all entities included in the result.
#### memo.query
`memo.query()` allows denormalizing [Queryable](#queryable) based on args alone, rather than a normalized input.
```ts
const data = memo.query(
Article,
args,
normalizedData,
);
```
## Queryable
`Queryable` Schemas allow store access without an endpoint. They achieve this using the
[queryKey](./Entity.md#queryKey) method that produces the results normally stored in the endpoint cache.
This enables their use in these additional cases:
- [useQuery()](https://dataclient.io/docs/api/useQuery) - Rendering in React
- [schema.Query()](./Query.md) - As input to produce a computed memoization.
- [ctrl.get](https://dataclient.io/docs/api/Controller#get)/[snap.get](https://dataclient.io/docs/api/Snapshot#get)
- [Managers](https://dataclient.io/docs/concepts/managers)
- React with [useController()](https://dataclient.io/docs/api/useController)
- [RestEndpoint.getOptimisticResponse](https://dataclient.io/rest/api/RestEndpoint#getoptimisticresponse)
- [Unit testing hooks](https://dataclient.io/docs/guides/unit-testing-hooks) with [renderDataHook()](https://dataclient.io/docs/api/renderDataHook)
- [memo.query()](#memoquery)
- Improve performance of [useSuspense](https://dataclient.io/docs/api/useSuspense), [useDLE](https://dataclient.io/docs/api/useDLE) by rendering before endpoint resolution
`Querables` include [Entity](./Entity.md), [Object](./Object.md), [All](./All.md), [Collection](./Collection.md), [Query](./Query.md),
[Union](./Union.md), and [Scalar](./Scalar.md). [Lazy](./Lazy.md) fields produce a Queryable via their [`.query`](./Lazy.md#query) accessor.
```ts
interface Queryable {
queryKey(
args: readonly any[],
unvisit: (schema: any, args: readonly any[]) => any,
delegate: IQueryDelegate,
// `{}` means non-void
): {};
}
```
## Schema Overview
| Data Type | Mutable | Schema | Description | [Queryable](./schema.md#queryable) |
| ------------------------------------------------------------------- | ------- | ------------------------------------- | --------------------------------------------------------------------------------------- | ---------------------------------- |
| [Object](https://en.wikipedia.org/wiki/Object_\(computer_science\)) | ✅ | [Entity](./Entity.md) | single _unique_ object | ✅ |
| [Object](https://en.wikipedia.org/wiki/Object_\(computer_science\)) | ✅ | [Union(Entity)](./Union.md) | polymorphic objects (`A \| B`) | ✅ |
| [Object](https://en.wikipedia.org/wiki/Object_\(computer_science\)) | 🛑 | [Object](./Object.md) | statically known keys | ✅ |
| [Object](https://en.wikipedia.org/wiki/Object_\(computer_science\)) | | [Invalidate(Entity)](./Invalidate.md) | [delete an entity](https://dataclient.io/docs/concepts/expiry-policy#invalidate-entity) | 🛑 |
| [List](https://en.wikipedia.org/wiki/List_\(abstract_data_type\)) | ✅ | [Collection(Array)](./Collection.md) | growable lists | ✅ |
| [List](https://en.wikipedia.org/wiki/List_\(abstract_data_type\)) | 🛑 | [Array](./Array.md) | immutable lists | 🛑 |
| [List](https://en.wikipedia.org/wiki/List_\(abstract_data_type\)) | | [All](./All.md) | list of all entities of a kind | ✅ |
| [Map](https://en.wikipedia.org/wiki/Associative_array) | ✅ | [Collection(Values)](./Collection.md) | growable maps | ✅ |
| [Map](https://en.wikipedia.org/wiki/Associative_array) | 🛑 | [Values](./Values.md) | immutable maps | 🛑 |
| [Scalar](https://en.wikipedia.org/wiki/Scalar_\(mathematics\)) | ✅ | [Scalar](./Scalar.md) | lens-dependent entity fields | ✅ |
| any | | [Query(Queryable)](./Query.md) | memoized custom transforms | ✅ |
| any | | [Lazy(Schema)](./Lazy.md) | deferred denormalization; [.query](./Lazy.md#query) is Queryable | 🛑 |
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack." | Stars: 196k | Updated | Claude CodeCodex | Verified | Install |
| ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read. | Stars: 193k | Updated | Claude CodeCodex | Verified | Install |
| ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report. | Stars: 193k | Updated | Claude CodeCodex | Verified | Install |
| ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt. | Stars: 193k | Updated | Claude CodeCodex | Verified | Install |