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/computed-properties.vue.md

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

# Computed Properties

## Singular computations

[Entity](./Entity.vue.md) classes are just normal classes, so any common derived data can just be added as
getters to the class itself.

```typescript
import { All, Entity, Query } from '@data-client/rest';

class User extends Entity {
  id = '';
  firstName = '';
  lastName = '';
  username = '';
  email = '';

  get fullName() {
    return `${this.firstName} ${this.lastName}`;
  }

  static key = 'User';
}
```

If the computations are expensive feel free to add some
[memoization](https://github.com/anywhichway/nano-memoize).

```typescript
import { All, Entity, Query } from '@data-client/rest';
import memoize from 'nano-memoize';

class User extends Entity {
  truelyExpensiveValue = memoize(() => {
    // compute that expensive thing!
  });
}
```

> **Tip**
>
> If you simply want to [deserialize a field](https://dataclient.io/rest/guides/network-transform#deserializing-fields) to a more useful form like [Temporal.Instant](https://tc39.es/proposal-temporal/docs/instant.html) or [BigNumber](https://github.com/MikeMcl/bignumber.js), you can use
> the declarative [static schema](https://dataclient.io/rest/guides/network-transform#deserializing-fields).
>
> ```typescript
> import { All, Entity, Query } from '@data-client/rest';
> import BigNumber from 'bignumber.js';
>
> class User extends Entity {
>   id = '';
>   firstName = '';
>   lastName = '';
>   createdAt = Temporal.Instant.fromEpochMilliseconds(0);
>   lifetimeBlinkCount = BigNumber(0);
>
>   static key = 'User';
>
>   static schema = {
>     createdAt: Temporal.Instant.from,
>     lifetimeBlinkCount: BigNumber,
>   };
> }
> ```

## Global computations

[Query](./Query.vue.md) derives data from many entities, like a cart's totals. This is known as an
_aggregate_. Define it once beside your resources, then read it anywhere with
[useQuery()](https://dataclient.io/vue/api/useQuery).

Files with a `route` are pages mounted at that path, with its params as props (vue-router `props: true`).

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

export class Product extends Entity {
  id = '';
  name = '';
  price = 0;
}
export const ProductResource = resource({
  path: '/products/:id',
  schema: Product,
});

/** A line in the cart, keyed by its product's id */
export class CartItem extends Entity {
  id = '';
  product = Product.fromJS();
  quantity = 1;

  get total() {
    return this.quantity * this.product.price;
  }

  static schema = { product: Product };
}
export const CartResource = resource({
  path: '/cart/items/:id',
  schema: CartItem,
  optimistic: true,
});

export const usd = { style: 'currency', currency: 'USD' } as const;
```

```ts title="getCartTotals" {6}
import { Query } from '@data-client/rest';
import { CartResource } from './resources/Cart';

export const freeShippingAt = 50;

export const getCartTotals = new Query(CartResource.getList.schema, items => {
  const count = items.reduce((sum, item) => sum + item.quantity, 0);
  const subtotal = items.reduce((sum, item) => sum + item.total, 0);
  const toFreeShipping = Math.max(0, freeShippingAt - subtotal);
  const shipping = subtotal && toFreeShipping ? 5 : 0;
  return {
    count,
    subtotal,
    shipping,
    total: subtotal + shipping,
    toFreeShipping,
  };
});
```

```html title="CartBadge.vue"
<script setup lang="ts">
  import { useQuery } from '@data-client/vue';
  import NumberFlow from '@number-flow/vue';
  import { getCartTotals } from './getCartTotals';
  import { usd } from './resources/Cart';

  const totals = useQuery(getCartTotals);
</script>

<template>
  <RouterLink v-if="totals" to="/cart" class="meta">
    {{ totals.count }} {{ totals.count === 1 ? 'item' : 'items' }} ·
    <NumberFlow :value="totals.subtotal" :format="usd" />
  </RouterLink>
</template>
```

```html title="FreeShipping.vue"
<script setup lang="ts">
  import { useQuery } from '@data-client/vue';
  import NumberFlow from '@number-flow/vue';
  import { freeShippingAt, getCartTotals } from './getCartTotals';
  import { usd } from './resources/Cart';

  const totals = useQuery(getCartTotals);
</script>

<template>
  <p v-if="totals" class="meta">
    <template v-if="totals.toFreeShipping > 0">
      Add <NumberFlow :value="totals.toFreeShipping" :format="usd" /> more
      for free shipping
    </template>
    <template v-else>Your order ships free</template>
    <progress :value="totals.subtotal" :max="freeShippingAt" />
  </p>
</template>
```

```html title="OrderSummary.vue"
<script setup lang="ts">
  import { useQuery } from '@data-client/vue';
  import NumberFlow from '@number-flow/vue';
  import { getCartTotals } from './getCartTotals';
  import { usd } from './resources/Cart';

  const totals = useQuery(getCartTotals);
</script>

<template>
  <dl v-if="totals" class="stats">
    <div>
      <dt>Subtotal</dt>
      <dd><NumberFlow :value="totals.subtotal" :format="usd" /></dd>
    </div>
    <div>
      <dt>Shipping</dt>
      <dd>
        <NumberFlow
          v-if="totals.shipping"
          :value="totals.shipping"
          :format="usd"
        />
        <template v-else>Free</template>
      </dd>
    </div>
    <div>
      <dt>Total</dt>
      <dd><NumberFlow :value="totals.total" :format="usd" /></dd>
    </div>
  </dl>
</template>
```

```html title="CheckoutButton.vue"
<script setup lang="ts">
  import { useQuery } from '@data-client/vue';
  import NumberFlow from '@number-flow/vue';
  import { getCartTotals } from './getCartTotals';
  import { usd } from './resources/Cart';

  const totals = useQuery(getCartTotals);
</script>

<template>
  <button v-if="totals" class="primary">
    Check out · <NumberFlow :value="totals.total" :format="usd" />
  </button>
</template>
```

```html title="QuantityStepper.vue"
<script setup lang="ts">
  import { useController, useQuery } from '@data-client/vue';
  import { CartItem, CartResource, Product } from './resources/Cart';

  const props = defineProps<{ product: Product }>();
  const ctrl = useController();
  const item = useQuery(CartItem, () => ({ id: props.product.id }));
  const add = () =>
    ctrl.fetch(CartResource.getList.push, {
      id: props.product.id,
      product: props.product,
      quantity: 1,
    });
  const setQuantity = (quantity: number) =>
    quantity ?
      ctrl.fetch(
        CartResource.partialUpdate,
        { id: props.product.id },
        { quantity },
      )
    : ctrl.fetch(CartResource.delete, { id: props.product.id });
</script>

<template>
  <span class="stepper">
    <template v-if="item">
      <button
        :aria-label="`Remove one ${product.name}`"
        @click="setQuantity(item.quantity - 1)"
      >
        −
      </button>
      <output>{{ item.quantity }}</output>
      <button
        :aria-label="`Add one ${product.name}`"
        @click="setQuantity(item.quantity + 1)"
      >
        +
      </button>
    </template>
    <button v-else :aria-label="`Add ${product.name}`" @click="add">
      Add
    </button>
  </span>
</template>
```

```html title="ShopPage.vue" route="/"
<script setup lang="ts">
  import { useSuspense } from '@data-client/vue';
  import FreeShipping from './FreeShipping.vue';
  import QuantityStepper from './QuantityStepper.vue';
  import { CartResource, ProductResource, usd } from './resources/Cart';

  const products = await useSuspense(ProductResource.getList);
  await useSuspense(CartResource.getList);
</script>

<template>
  <FreeShipping />
  <div class="list">
    <div v-for="product in products" :key="product.id" class="listItem">
      <div>
        {{ product.name }}
        <div class="meta">{{ product.price.toLocaleString('en-US', usd) }}</div>
      </div>
      <QuantityStepper :product="product" />
    </div>
  </div>
</template>
```

```html title="CartPage.vue" route="/cart"
<script setup lang="ts">
  import { useSuspense } from '@data-client/vue';
  import NumberFlow from '@number-flow/vue';
  import CheckoutButton from './CheckoutButton.vue';
  import FreeShipping from './FreeShipping.vue';
  import OrderSummary from './OrderSummary.vue';
  import QuantityStepper from './QuantityStepper.vue';
  import { CartResource, usd } from './resources/Cart';

  const items = await useSuspense(CartResource.getList);
</script>

<template>
  <p v-if="!items.length" class="meta">Your cart is empty</p>
  <template v-else>
    <div class="list">
      <div v-for="item in items" :key="item.id" class="listItem">
        <div>{{ item.product.name }}</div>
        <QuantityStepper :product="item.product" />
        <span class="meta">
          <NumberFlow :value="item.total" :format="usd" />
        </span>
      </div>
    </div>
    <FreeShipping />
    <OrderSummary />
    <CheckoutButton />
  </template>
</template>
```

```html title="Store.vue" layout
<script setup lang="ts">
  import { useFetch } from '@data-client/vue';
  import CartBadge from './CartBadge.vue';
  import { CartResource } from './resources/Cart';

  // every page shows the cart's totals, so the cart loads with the app
  useFetch(CartResource.getList);
</script>

<template>
  <header class="appHeader">
    <h1 class="appTitle">Daily Grind</h1>
    <CartBadge />
  </header>
  <nav>
    <RouterLink to="/">Shop</RouterLink>
    <RouterLink to="/cart">Cart</RouterLink>
  </nav>
  <RouterView v-slot="{ Component }">
    <Suspense timeout="0">
      <component :is="Component" />
      <template #fallback><Loading /></template>
    </Suspense>
  </RouterView>
</template>
```

Here the cart badge, free-shipping bar, order summary and checkout button all read `getCartTotals`.
It runs once per change, however many components read it, and returns the same object until a
`CartItem` or `Product` it read changes. So every view agrees, even mid
[optimistic update](https://dataclient.io/rest/api/resource#optimistic).

Do not compute aggregates in components, where each copy can drift. Instead, put them in a `Query`.
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: 197kUpdated 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: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 194kUpdated 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: 194kUpdated Claude CodeCodexVerifiedInstall