# Entities (https://0758e0c7.effetch-query.pages.dev/docs/mutations/entities)

A todo is often in many queries at the same time: its own detail, a list
per filter, each loaded page of an infinite list. An entity writes it in
all of them. Say once what identifies it, beside its schema:

The examples import `api.ts` and `todos.ts` from [Getting started](https://0758e0c7.effetch-query.pages.dev/docs/getting-started).

```ts entities.ts
import { Entity } from "@monarcode/effetch-query";

import { Todo } from "./api.js";

export const Todos = Entity.make(Todo, { id: (todo) => todo.id });
```

`Entity.make` takes the schema and an `Entity.MakeOptions`, whose `id`
gets a todo's ID. A `Schema.Class` works as the schema too. Then write the
todo, or read it, by ID:

- `Entity.update(Todos, id, f)` writes `f` of the todo into every cached
  query that holds it.
- `Entity.set(Todos, todo)` writes a whole todo, such as a mutation's
  result, over every copy with its ID. It adds it to no list: invalidate
  the lists it should join.
- `Entity.remove(Todos, id)` drops it from lists and records, and empties
  an optional or `NullOr` field. A required field and a detail query's
  whole value keep it. Totals don't change, so invalidate the lists too,
  and count an infinite query's next page from its params, not its length.
- `Entity.get(Todos, id)` reads the newest cached copy, as an `Option`.
  Where copies differ, the one from the query fetched or written last
  wins. Use it for a detail query's placeholder
  ([Show a placeholder](https://0758e0c7.effetch-query.pages.dev/docs/queries/placeholders)).

Writes are recorded like `Query.update`'s, so in `optimistic` they're
undone if the run fails:

```ts
import { Fetch } from "@monarcode/effetch";
import { Entity } from "@monarcode/effetch-query";

import { Todos } from "./entities.js";
import { api, todos } from "./todos.js";

export const deleteTodo = api.mutation(Fetch.endpoint("DELETE /todos/:id"), {
  optimistic: ({ params }) => Entity.remove(Todos, Number(params.id)),
  // The lists' totals come from the server.
  invalidates: [todos],
});
```

IDs are compared with `Equal.equals`, so convert a route param first
(`Number(params.id)`); a number and a string don't match.

**What an entity write reaches.** Nothing is normalized: each query keeps
its own value, and an entity write maps it. A write keeps each query's
age, so it doesn't make a stale query fresh or stop it from refetching. A
query whose value doesn't change isn't written. If `f` throws, nothing is
written and the Effect dies with the defect. Some queries are left to
their next fetch:

- a query that's invalidated and not in use, or that shows a failure;
- a query without a value;
- a query without a schema.

A query is found through its schema: an endpoint's `output`, or `schema`
on `Query.make`, `Query.family` and infinite queries. So:

- The todo is found in arrays, tuples, records, struct fields, optional and
  `NullOr` fields, unions, nested and recursive schemas, `Schema.Class`
  instances and infinite queries' pages, on the decoded side of a schema
  that transforms.
- It's found by its schema: `Todo`, or `Todo` with annotations or checks
  added. Another schema with the same fields, such as
  `Schema.Struct({ ...Todo.fields, extra })`, isn't the entity.
- It isn't found inside `Option`, `Map` or other such types.
- A value sent from the server is reached once a query reads it.

## Responses in other shapes

Endpoints often return one record in different shapes: a search row with
its own field names, a detail wrapped in `data`. Decode each one to the
entity's schema with `Schema.decodeTo`. An entity is found on the decoded
side of a schema, so it's found in every query whose schema decodes to
it, whatever the wire shape:

```ts
import * as Schema from "effect/Schema";
import * as SchemaTransformation from "effect/SchemaTransformation";

import { Fetch } from "@monarcode/effetch";

import { Todo } from "./api.js";
import { api } from "./todos.js";

// What GET /search/todos sends for each todo. Only the fields that are
// read are declared: a response's other fields are ignored.
const SearchRow = Schema.Struct({
  todo_id: Schema.Finite,
  label: Schema.String,
  completed: Schema.Boolean,
});

// A search row as a Todo, so the Todos entity finds it.
export const TodoFromSearchRow = SearchRow.pipe(
  Schema.decodeTo(
    Todo,
    SchemaTransformation.transform({
      decode: (row) => ({
        id: row.todo_id,
        title: row.label,
        done: row.completed,
      }),
      // The mirror of decode, for server rendering.
      encode: (todo) => ({
        todo_id: todo.id,
        label: todo.title,
        completed: todo.done,
      }),
    }),
  ),
);

export const searchResults = api.query(
  Fetch.endpoint("GET /search/todos", {
    output: Schema.Array(TodoFromSearchRow),
  }),
);
```

`Entity.update(Todos, …)` now writes the search results too, and
`Entity.get` reads them. Three things make it work:

- **Decode to the entity's own schema.** Import the one `Todo` the entity
  was made with. Another schema with the same fields isn't the entity.
- **Decode IDs to one type.** IDs are compared with `Equal.equals`, so a
  todo whose ID is `"1"` in one response and `1` in another is two todos.
- **Write `encode` too, if you render on the server.** A query's value is
  sent to the browser in its wire shape, so its schema must encode the
  todo back ([Schemas that transform](https://0758e0c7.effetch-query.pages.dev/docs/server-rendering/transforming-schemas)). In an app
  that only runs in the browser, `encode` is never called.