Skip to content

reactive/data-client / .agents/skills/data-client-schema

data-client-schema

Verified

Model 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.

FileKindSize
SKILL.mdskill md11.9 KB
evals/evals.jsonconfig17.2 KB
references.jsonconfig1.1 KB
references/All.mdmarkdown5.9 KB
references/All.vue.mdmarkdown6.4 KB
references/Array.mdmarkdown5.3 KB
references/Array.vue.mdmarkdown5.9 KB
references/Collection.mdmarkdown18.9 KB
references/Collection.vue.mdmarkdown18.9 KB
references/Entity.mdmarkdown22.4 KB
references/Entity.vue.mdmarkdown22.3 KB
references/EntityMixin.mdmarkdown13.6 KB
references/EntityMixin.vue.mdmarkdown13.6 KB
references/Invalidate.mdmarkdown6.1 KB
references/Invalidate.vue.mdmarkdown6.1 KB
references/Lazy.mdmarkdown4.6 KB
references/Lazy.vue.mdmarkdown4.7 KB
references/Object.mdmarkdown1.5 KB
references/Object.vue.mdmarkdown1.5 KB
references/Query.mdmarkdown9.9 KB
references/Query.vue.mdmarkdown10.2 KB
references/Scalar.mdmarkdown13.1 KB
references/Scalar.vue.mdmarkdown12.8 KB
references/Union.mdmarkdown4.7 KB
references/Union.vue.mdmarkdown4.7 KB
references/Values.mdmarkdown5.4 KB
references/Values.vue.mdmarkdown5.9 KB
references/_ScalarDemo.mdmarkdown3.6 KB
references/_ScalarDemo.vue.mdmarkdown3.5 KB
references/computed-properties.mdmarkdown9.9 KB
references/computed-properties.vue.mdmarkdown9.9 KB
references/partial-entities.mdmarkdown3.8 KB
references/partial-entities.vue.mdmarkdown3.8 KB
references/relational-data.mdmarkdown16.2 KB
references/relational-data.vue.mdmarkdown15.7 KB
references/schema.mdmarkdown9.5 KB
references/schema.vue.mdmarkdown9.5 KB
references/side-effects.mdmarkdown2.5 KB
references/side-effects.vue.mdmarkdown2.6 KB
references/sorting-client-side.mdmarkdown2.7 KB
references/sorting-client-side.vue.mdmarkdown2.8 KB
references/validation.mdmarkdown4.3 KB
references/validation.vue.mdmarkdown4.3 KB

references/Query.vue.md

View on GitHub
<!-- Generated by `yarn build:skills` from docs/rest/api/Query.md (vue). Edit the source doc, not this file. -->

# Query

`Query` provides programmatic access to the Reactive Data Client cache while maintaining
the same high performance and referential equality guarantees expected of Reactive Data Client.

`Query` can be rendered using [schema lookup composable useQuery()](https://dataclient.io/vue/api/useQuery)

## Query members

### schema

[Schema](./schema.vue.md) used to retrieve/denormalize data from the Reactive Data Client cache.
This accepts any [Queryable](./schema.vue.md#queryable) schema: [Entity](./Entity.vue.md), [All](./All.vue.md), [Collection](./Collection.vue.md), [Query](./Query.vue.md),
[Union](./Union.vue.md), [Scalar](./Scalar.vue.md), and [Object](./Object.vue.md) schemas for joining multiple entities.
[Lazy](./Lazy.vue.md) fields produce a Queryable via their [`.query`](./Lazy.vue.md#query) accessor.

### process(entries, ...args) {#process}

Takes the (denormalized) response as entries and arguments and returns the new
response for use with [useQuery](https://dataclient.io/vue/api/useQuery)

`useQuery(query, ...args)` passes every argument to the Query's `schema` and to `process`, after the entries, so
check each argument against both. The schema finds its data with the arguments, as `useQuery(schema, ...args)`
would; when it finds nothing, `useQuery()` returns `undefined`. Give `process` an argument of its own only if the
schema ignores it: [All](./All.vue.md) ignores every argument.

## Usage

### Maintaining sort after creates {#sorting}

```ts title="getPosts" {17-24}
import { Collection, Entity, Query, RestEndpoint } from '@data-client/rest';

export class Post extends Entity {
  id = '';
  title = '';
  group = '';
  author = '';
}

export const getPosts = new RestEndpoint({
  path: '/:group/posts',
  searchParams: {} as { orderBy?: string; author?: string },
  schema: new Query(
    new Collection([Post], {
      nonFilterArgumentKeys: /orderBy/,
    }),
    (posts, { orderBy } = {}) => {
      if (orderBy) {
        return [...posts].sort((a, b) =>
          a[orderBy].localeCompare(b[orderBy]),
        );
      }
      return posts;
    },
  ),
});
```

```html title="NewPost.vue"
<script setup lang="ts">
  import { useController, useLoading } from '@data-client/vue';
  import { getPosts } from './getPosts';

  const props = defineProps<{ author: string }>();
  const ctrl = useController();

  const [handlePress, loading] = useLoading(async (e: KeyboardEvent) => {
    if (e.key === 'Enter') {
      const input = e.currentTarget as HTMLInputElement;
      const title = input.value;
      input.value = '';
      await ctrl.fetch(
        getPosts.push,
        { group: 'react' },
        {
          title,
          author: props.author,
        },
      );
    }
  });
</script>

<template>
  <input
    type="text"
    aria-label="New post title"
    placeholder="Post title"
    :aria-busy="loading"
    @keydown="handlePress"
  />
</template>
```

```html title="PostList.vue" {9}
<script setup lang="ts">
  import { useSuspense } from '@data-client/vue';
  import { getPosts } from './getPosts';
  import NewPost from './NewPost.vue';

  const props = defineProps<{ author: string }>();
  const posts = await useSuspense(getPosts, () => ({
    author: props.author,
    orderBy: 'title',
    group: 'react',
  }));
</script>

<template>
  <div>
    <div v-for="post in posts" :key="post.pk()">{{ post.title }}</div>
    <NewPost :author="author" />
  </div>
</template>
```

```html title="UserList.vue"
<script setup lang="ts">
  import PostList from './PostList.vue';

  const users = ['bob', 'clara'];
</script>

<template>
  <div>
    <section v-for="user in users" :key="user">
      <h3>{{ user }}</h3>
      <PostList :author="user" />
    </section>
  </div>
</template>
```

### Aggregates

```ts title="resources/User"
import { Entity, resource } from '@data-client/rest';

export class User extends Entity {
  id = '';
  name = '';
  isAdmin = false;
}
export const UserResource = resource({
  path: '/users/:id',
  schema: User,
});
```

```html title="UsersPage.vue"
<script lang="ts">
  import { All, Query } from '@data-client/rest';
  import { UserResource, User } from './resources/User';

  const countUsers = new Query(
    new All(User),
    (entries, { isAdmin } = {}) => {
      if (isAdmin !== undefined)
        return entries.filter(user => user.isAdmin === isAdmin).length;
      return entries.length;
    },
  );
</script>

<script setup lang="ts">
  import { useQuery, useFetch } from '@data-client/vue';

  useFetch(UserResource.getList);
  const userCount = useQuery(countUsers);
  const adminCount = useQuery(countUsers, { isAdmin: true });
</script>

<template>
  <div v-if="userCount === undefined">No users in cache yet</div>
  <div v-else>
    <div>Total users: {{ userCount }}</div>
    <div>Total admins: {{ adminCount }}</div>
  </div>
</template>
```

### Rearranging data with groupBy aggregations {#groupby}

```ts title="resources/User"
import { Entity, resource } from '@data-client/rest';

export class User extends Entity {
  id = 0;
  username = '';
  name = '';
  email = '';
  website = '';
}
export const UserResource = resource({
  urlPrefix: 'https://jsonplaceholder.typicode.com',
  path: '/users/:id',
  schema: User,
});
```

```ts title="resources/Todo"
import { Entity, resource } from '@data-client/rest';
import { User } from './User';

export class Todo extends Entity {
  id = 0;
  userId = 0;
  user? = User.fromJS({});
  title = '';
  completed = false;

  static schema = {
    user: User,
  };
  static process(input) {
    return { ...input, user: input.userId };
  }
}
export const TodoResource = resource({
  urlPrefix: 'https://jsonplaceholder.typicode.com',
  path: '/todos/:id',
  schema: Todo,
  searchParams: {} as { userId?: string | number } | undefined,
});
```

```html title="TodoByUser.vue"
<script setup lang="ts">
  import { useQuery } from '@data-client/vue';
  import { User } from './resources/User';
  import type { Todo } from './resources/Todo';

  const props = defineProps<{ userId: string; todos: Todo[] }>();
  const user = useQuery(User, () => ({ id: props.userId }));

  function tasksRemaining(todos: Todo[]) {
    return todos.filter(({ completed }) => !completed).length;
  }
</script>

<template>
  <!-- don't bother if no user is loaded yet -->
  <div v-if="user">
    <h3>{{ user.name }} has {{ tasksRemaining(todos) }} tasks left</h3>
    <div v-for="todo in todos.slice(0, 3)" :key="todo.pk()">
      {{ todo.title }} by {{ todo.user === user ? todo.user.name : '' }}
    </div>
  </div>
</template>
```

```html title="TodoJoined.vue"
<script lang="ts">
  import { Query } from '@data-client/rest';
  import { TodoResource } from './resources/Todo';
  import { UserResource } from './resources/User';

  const groupTodoByUser = new Query(
    TodoResource.getList.schema,
    todos => Object.groupBy(todos, todo => todo.userId),
  );
</script>

<script setup lang="ts">
  import { useQuery, useFetch, useSuspense } from '@data-client/vue';
  import TodoByUser from './TodoByUser.vue';

  // start both fetches in parallel
  useFetch(UserResource.getList);
  await useSuspense(TodoResource.getList);
  await useSuspense(UserResource.getList);
  const todosByUser = useQuery(groupTodoByUser);
</script>

<template>
  <div v-if="!todosByUser">Todos not found</div>
  <div v-else>
    <TodoByUser
      v-for="userId in Object.keys(todosByUser)"
      :key="userId"
      :userId="userId"
      :todos="todosByUser[userId]"
    />
  </div>
</template>
```

### Object Schema Joins {#object-schema-joins}

`Query` can take [Object Schemas](./Object.vue.md), enabling joins across multiple entity types. This allows you to combine data from different entities in a single query.

```ts title="resources/Ticker"
import { Entity, resource } from '@data-client/rest';

export class Ticker extends Entity {
  product_id = '';
  price = 0;
  pk() { return this.product_id; }
}

export const TickerResource = resource({
  path: '/tickers/:product_id',
  schema: Ticker,
});
```

```ts title="resources/Stats"
import { Entity, resource } from '@data-client/rest';

export class Stats extends Entity {
  product_id = '';
  last = 0;
  pk() { return this.product_id; }
}

export const StatsResource = resource({
  path: '/stats/:product_id',
  schema: Stats,
});
```

```html title="PriceDisplay.vue"
<script lang="ts">
  import { Query } from '@data-client/rest';
  import { TickerResource, Ticker } from './resources/Ticker';
  import { StatsResource, Stats } from './resources/Stats';

  // Join Ticker and Stats by product_id
  const queryPrice = new Query(
    { ticker: Ticker, stats: Stats },
    ({ ticker, stats }) => ticker?.price ?? stats?.last,
  );
</script>

<script setup lang="ts">
  import { useQuery, useFetch } from '@data-client/vue';
  import NumberFlow from '@number-flow/vue';

  const props = defineProps<{ productId: string }>();
  useFetch(TickerResource.get, () => ({ product_id: props.productId }));
  useFetch(StatsResource.get, () => ({ product_id: props.productId }));
  const price = useQuery(queryPrice, () => ({ product_id: props.productId }));
</script>

<template>
  <dl class="stats">
    <div>
      <dt>{{ productId }}</dt>
      <dd>
        <span v-if="price === undefined" class="skeleton" />
        <NumberFlow
          v-else
          :value="price"
          :format="{ style: 'currency', currency: 'USD' }"
        />
      </dd>
    </div>
  </dl>
</template>
```

### Fallback joins

In this case `Ticker` is constantly updated from a websocket stream. However, there is no bulk/list
fetch for `Ticker` - making it inefficient for getting the prices on a list view.

So in this case we can fetch a list of `Stats` as a fallback since it has price data as well.

Example app: [coin-app](https://github.com/reactive/data-client/tree/master/examples/coin-app) ([`src/pages/Home/CurrencyList.tsx`](https://github.com/reactive/data-client/blob/master/examples/coin-app/src/pages/Home/CurrencyList.tsx), [`src/pages/Home/AssetPrice.tsx`](https://github.com/reactive/data-client/blob/master/examples/coin-app/src/pages/Home/AssetPrice.tsx), [`src/resources/fallbackQueries.ts`](https://github.com/reactive/data-client/blob/master/examples/coin-app/src/resources/fallbackQueries.ts))
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: 196kUpdated Claude CodeCodexVerifiedInstall
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: 193kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 193kUpdated Claude CodeCodexVerifiedInstall
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: 193kUpdated Claude CodeCodexVerifiedInstall