# Controller

`Controller` gives type-safe access to the Reactive Data Client [store and its lifecycle](https://dataclient.io/vue/api/Manager.md#control-flow).
Each store has one `Controller`.

`Controller` memoizes denormalization for global referential equality: unchanged store data gives the same object
wherever it is read. This keeps rendering and lookups fast.

`Controller` is provided:

- [Managers](https://dataclient.io/vue/api/Manager.md) as the first argument in [Manager.middleware](https://dataclient.io/vue/api/Manager.md#middleware)
- Vue with [useController()](https://dataclient.io/vue/api/useController.md)
- [Unit testing composables](https://dataclient.io/vue/guides/unit-testing-composables.md) with `renderDataCompose()` from `@data-client/vue/test`

```ts
class Controller {
  /*************** Action Dispatchers ***************/
  fetch(endpoint, ...args): ReturnType<E>;
  fetchIfStale(endpoint, ...args): Promise<Denormalize<E['schema']>>;
  expireAll({ testKey }): Promise<void>;
  invalidate(endpoint, ...args): Promise<void>;
  invalidateAll({ testKey }): Promise<void>;
  resetEntireStore(): Promise<void>;
  set(queryable, ...args, value): Promise<void>;
  set([Entity], rows): Promise<void>;
  setResponse(endpoint, ...args, response): Promise<void>;
  setError(endpoint, ...args, error): Promise<void>;
  resolve(endpoint, { args, response, fetchedAt, error }): Promise<void>;
  subscribe(endpoint, ...args): Promise<void>;
  unsubscribe(endpoint, ...args): Promise<void>;
  /*************** Data Access ***************/
  get(queryable, ...args, state): DenormalizeNullable<typeof queryable> | undefined;
  getResponse(endpoint, ...args, state): { data; expiryStatus; expiresAt };
  getError(endpoint, ...args, state): ErrorTypes | undefined;
  snapshot(state: State<unknown>, fetchedAt?: number): SnapshotInterface;
  getState(): State<unknown>;
}
```

## Action Dispatchers

### fetch(endpoint, ...args) {#fetch}

Fetches the endpoint with the given args. When the fetch completes, the response or error goes into the cache.

**Create**

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

  const ctrl = useController();

  const handleSubmit = (e: Event) =>
    ctrl.fetch(
      PostResource.getList.push,
      new FormData(e.target as HTMLFormElement),
    );
</script>

<template>
  <form @submit.prevent="handleSubmit"><!-- ... --></form>
</template>
```

**Update**

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

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

  const handleSubmit = (e: Event) =>
    ctrl.fetch(
      PostResource.update,
      { id: props.id },
      new FormData(e.target as HTMLFormElement),
    );
</script>

<template>
  <form @submit.prevent="handleSubmit"><!-- ... --></form>
</template>
```

**Delete**

```html title="PostListItem.vue"
<script setup lang="ts">
  import { useController } from '@data-client/vue';
  import { useRouter } from 'vue-router';
  import { Post, PostResource } from './PostResource';

  const props = defineProps<{ post: Post }>();
  const ctrl = useController();
  const router = useRouter();

  const handleDelete = async () => {
    await ctrl.fetch(PostResource.delete, { id: props.post.id });
    router.push('/');
  };
</script>

<template>
  <div>
    <h3>{{ post.title }}</h3>
    <button @click="handleDelete">X</button>
  </div>
</template>
```

> **Tip**
>
> `fetch` has the same return value as the [Endpoint](https://dataclient.io/rest/api/Endpoint.md) passed to it.
> With a schema, it returns the denormalized value.
>
> ```ts
> const controller = useController();
>
> const post = await controller.fetch(
>   PostResource.getList.push,
>   createPayload,
> );
> post.title;
> post.pk();
> ```

#### Endpoint.sideEffect

[sideEffect](https://dataclient.io/rest/api/Endpoint.md#sideeffect) changes how `fetch()` behaves:

##### true

- Resolves _before_ the cache update is [committed](https://react.dev/learn/render-and-commit#step-3-react-commits-changes-to-the-dom).
- Every call starts a new fetch.
- Unawaited, it rejects unhandled, since no component reads its error. Await it, or use
  [useLoading()](https://dataclient.io/vue/api/useLoading.md) to show the error.

##### false | undefined

- Resolves _after_ the cache update is [committed](https://react.dev/learn/render-and-commit#step-3-react-commits-changes-to-the-dom).
- Identical requests are deduplicated, so only one is in flight at a time.
  - To start a _new_ request, abort the one in flight first.
- Safe unawaited: the error is stored for components reading that endpoint, so it never reaches global
  unhandled-rejection handlers ([report it](https://dataclient.io/vue/concepts/managers.md#error-reporting) instead). `await` still rejects.

### fetchIfStale(endpoint, ...args) {#fetchIfStale}

Fetches only when the data is missing, [stale](https://dataclient.io/vue/concepts/expiry-policy.md#stale) or [invalid](https://dataclient.io/vue/concepts/expiry-policy.md#invalid),
and always returns a Promise of the latest fetch's outcome. This avoids overfetching fresh data when prefetching.

| Cache                                                                                                            | Fetches                     | `await` gives                                                                                         | Not awaited                                 |
| ---------------------------------------------------------------------------------------------------------------- | --------------------------- | ----------------------------------------------------------------------------------------------------- | ------------------------------------------- |
| Missing, stale or invalid                                                                                        | Yes, like [fetch()](#fetch) | The fetched data, or rejects with its error                                                           | The error is stored; no unhandled rejection |
| Fresh                                                                                                            | No                          | The cached data                                                                                       | Nothing happens                             |
| The latest fetch failed within [errorExpiryLength](https://dataclient.io/rest/api/Endpoint.md#errorexpirylength) | No                          | Rejects with that error, like [useSuspense()](https://dataclient.io/vue/api/useSuspense.md) throws it | Nothing happens                             |

So prefetches don't need to be awaited or caught: components reading that endpoint show a stored error as usual.
Unawaited failures don't reach global unhandled-rejection handlers, so report fetch errors with an
[error reporting Manager](https://dataclient.io/vue/concepts/managers.md#error-reporting). A `.then()` chained onto the result makes a new
Promise, so end that chain with `.catch()`.

```ts
// start a secondary request without waiting for it
controller.fetchIfStale(CommentResource.getList, { issueId });
// wait for the data; rejects if that fetch fails
const issue = await controller.fetchIfStale(IssueResource.get, { id: issueId });
```

To check whether data is cached and fresh without fetching, read [getResponse()](#getResponse) synchronously.

### expireAll({ testKey }) {#expireAll}

Sets all responses' [expiry status](https://dataclient.io/vue/concepts/expiry-policy.md) matching `testKey` to [Stale](https://dataclient.io/vue/concepts/expiry-policy.md#stale).

Use it to refresh only the data on screen when the cache holds many sets of args.

```html title="CreateTrade.vue"
<script setup lang="ts">
  import { useController } from '@data-client/vue';
  import { AccountResource, TradeResource, type Trade } from './resources';
  import TradeForm from './TradeForm.vue';

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

  const handleTrade = async (trade: Trade) => {
    await ctrl.fetch(
      TradeResource.getList.push,
      { user: props.userId },
      trade,
    );
    ctrl.expireAll(AccountResource.get);
    ctrl.expireAll(AccountResource.getList);
  };
</script>

<template>
  <TradeForm @submit="handleTrade" />
</template>
```

> **Tip**
>
> Often it is better to [include mutation side effects in the mutation response](https://dataclient.io/rest/guides/side-effects.md). This
> reduces load, improves performance and keeps state consistent.

### invalidate(endpoint, ...args) {#invalidate}

Forces refetching on [useSuspense](https://dataclient.io/vue/api/useSuspense.md) with the same Endpoint
and parameters. Mounted components [keep showing their current data](https://dataclient.io/vue/concepts/expiry-policy.md#invalidate)
until the refetch resolves.

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

  const props = defineProps<{ id: string }>();
  const ctrl = useController();
  const article = await useSuspense(ArticleResource.get, () => ({
    id: props.id,
  }));
</script>

<template>
  <div>
    <h1>{{ article.title }}</h1>
    <button @click="ctrl.invalidate(ArticleResource.get, { id })">
      Refetch
    </button>
  </div>
</template>
```

> **Tip: Show the Suspense fallback again**
>
> Remount the component with a new `key` after invalidating; the new instance suspends on the invalid data.
> `timeout="0"` makes `<Suspense>` show its fallback while it waits instead of the old content. Remounting
> resets the component's local state.
>
> ```html title="ArticlePage.vue"
> <script setup lang="ts">
>   import { ref } from 'vue';
>   import { useController } from '@data-client/vue';
>   import { ArticleResource } from './ArticleResource';
>   import ArticleName from './ArticleName.vue';
>
>   const props = defineProps<{ id: string }>();
>   const ctrl = useController();
>   const remountKey = ref(0);
>
>   async function reload() {
>     await ctrl.invalidate(ArticleResource.get, { id: props.id });
>     remountKey.value++;
>   }
> </script>
>
> <template>
>   <button @click="reload">Reload</button>
>   <Suspense timeout="0">
>     <ArticleName :key="remountKey" :id="id" />
>     <template #fallback><Loading /></template>
>   </Suspense>
> </template>
> ```

> **Tip: Invalidate many endpoints at once**
>
> Use [schema.Invalidate](https://dataclient.io/rest/api/Invalidate.md) to invalidate every endpoint that contains a given entity.
>
> For REST, try [Resource.delete](https://dataclient.io/rest/api/resource.md#delete).
>
> ```ts
> // deletes MyResource(5)
> // this will refetch MyResource.get({id: '5'})
> // and remove it from MyResource.getList
> controller.setResponse(MyResource.delete, { id: '5' }, { id: '5' });
> ```

### invalidateAll({ testKey }) {#invalidateAll}

[Invalidates](https://dataclient.io/vue/concepts/expiry-policy.md#invalid) all [endpoint keys](https://dataclient.io/rest/api/RestEndpoint.md#key) matching `testKey`.

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

  const props = defineProps<{ id: string }>();
  const ctrl = useController();
  const article = await useSuspense(ArticleResource.get, () => ({
    id: props.id,
  }));
</script>

<template>
  <div>
    <h1>{{ article.title }}</h1>
    <button @click="ctrl.invalidateAll(ArticleResource.get)">
      Refetch
    </button>
  </div>
</template>
```

The code below invalidates only GET endpoints on the test.com domain. Other domains stay in the cache.

```ts
const myDomain = 'http://test.com';
const testKey = (key: string) => key.startsWith(`GET ${myDomain}`);

function useLogout() {
  const ctrl = useController();
  return () => ctrl.invalidateAll({ testKey });
}
```

Also clear the cache on 401 (unauthorized) with [LogoutManager](https://dataclient.io/vue/api/LogoutManager.md).

```ts title="main.ts"
import { createApp } from 'vue';
import {
  DataClientPlugin,
  LogoutManager,
  getDefaultManagers,
} from '@data-client/vue';
import App from './App.vue';
import { unAuth } from '../authentication';

const myDomain = 'http://test.com';
const testKey = (key: string) => key.startsWith(`GET ${myDomain}`);

const managers = () => [
  new LogoutManager({
    handleLogout(controller) {
      // call custom unAuth function we defined
      unAuth();
      // still reset the store
      controller.invalidateAll({ testKey });
    },
  }),
  ...getDefaultManagers(),
];

const app = createApp(App);
app.use(DataClientPlugin, { managers });
app.mount('#app');
```

### resetEntireStore() {#resetEntireStore}

Clears the entire Reactive Data Client cache. Responses to fetches in flight are not stored. Those fetches reject with a `ResetError` (`error.name === 'ResetError'`), except `sideEffect` fetches, which still settle with their own result or error.

Use it when a user logs out or the authenticated user changes.

```html title="UserName.vue"
<script setup lang="ts">
  import { useController, useSuspense } from '@data-client/vue';
  import { CurrentUserResource } from './CurrentUserResource';
  import { impersonateUser } from './auth';

  const USER_NUMBER_ONE: string = '1111';

  const user = await useSuspense(CurrentUserResource.get);
  const ctrl = useController();

  const becomeAdmin = () => {
    // Changes the current user
    impersonateUser(USER_NUMBER_ONE);
    ctrl.resetEntireStore();
  };
</script>

<template>
  <div>
    <h1>{{ user.name }}</h1>
    <button @click="becomeAdmin">Be Number One</button>
  </div>
</template>
```

### set(queryable, ...args, value) {#set}

Updates any [Queryable](https://dataclient.io/rest/api/schema.md#queryable) [Schema](https://dataclient.io/rest/api/schema.md#schema-overview), or many entities at once with an [Array](https://dataclient.io/rest/api/Array.md) or [Values](https://dataclient.io/rest/api/Values.md) schema.

```ts
ctrl.set(
  Todo,
  // which Todo to update
  { id: '5' },
  // merge this data into the Todo in the store
  { id: '5', title: 'tell me friends how great Data Client is' },
);
```

The value is typed by the schema: an [Entity](https://dataclient.io/rest/api/Entity.md) takes its fields (numbers and strings may be either),
while a [Collection](https://dataclient.io/rest/api/Collection.md) or [All](https://dataclient.io/rest/api/All.md) takes a list of rows. A [Query](https://dataclient.io/rest/api/Query.md)
takes the input of the schema it wraps, since `set()` normalizes that schema rather than reversing `process()`.

```ts
ctrl.set(TodoResource.getList.schema, [{ id: '5', completed: true }]);
```

[Collection.push](https://dataclient.io/rest/api/Collection.md#push) and [unshift](https://dataclient.io/rest/api/Collection.md#unshift) take the Collection's args,
which pick the lists to add to, and one row or a list of rows.

```ts
ctrl.set(TodoResource.getList.schema.push, { userId: '1' }, [
  { id: '6', title: 'Buy milk' },
  { id: '7', title: 'Walk dog' },
]);
```

> **Note: Unions**
>
> When each member declares its discriminator as a literal (like `readonly type = 'first'`), a
> [Union](https://dataclient.io/rest/api/Union.md) row is checked against the member it selects, so `{ type: 'first', secondField: 1 }` is an
> error. Only declared fields are accepted, so a key read by a
> `schemaAttribute` function must be declared on each member.

Pass a function to derive the value from the stored one. This [prevents race conditions](https://react.dev/reference/react/useState#updating-state-based-on-the-previous-state).

```ts
const id = '2';
ctrl.set(Article, { id }, article => ({ id, votes: article.votes + 1 }));
```

#### set(\[Entity], rows) {#set-array}

Pass an [Array](https://dataclient.io/rest/api/Array.md) schema (`[Todo]` or `new schema.Array(Todo)`) and a list of rows to update
many entities in one store update. Each row merges with its stored entity; entities not in the list are untouched.

```ts
ctrl.set(
  [Todo],
  [
    { id: '5', completed: true },
    { id: '6', completed: false },
  ],
);
```

Rows are typed by the Entity's fields; numbers and strings may be either, and object, array and Date values are not
checked since rows are raw input.

For lists that mix Entity types, use a [Union](https://dataclient.io/rest/api/Union.md); each row is stored by its `type`:

```ts
const Feed = new schema.Union({ post: Post, comment: Comment }, 'type');

ctrl.set(
  [Feed],
  [
    { id: '1', type: 'post', title: 'Hello' },
    { id: '7', type: 'comment', body: 'Nice!' },
  ],
);
```

To delete many entities at once, use [Invalidate](https://dataclient.io/rest/api/Invalidate.md#batch-invalidation); rows only need their pk
fields:

```ts
ctrl.set([new schema.Invalidate(Todo)], [{ id: '5' }, { id: '6' }]);
```

To delete one, pass the Invalidate schema and its row:

```ts
ctrl.set(new schema.Invalidate(Todo), { id: '5' });
```

[Values](https://dataclient.io/rest/api/Values.md) schemas take an object of rows instead:

```ts
ctrl.set(new schema.Values(Todo), {
  '5': { id: '5', completed: true },
  '6': { id: '6', completed: false },
});
```

Array, Values and Invalidate schemas take no `args` (so [Entity.pk()](https://dataclient.io/rest/api/Entity.md#pk) and [Entity.process()](https://dataclient.io/rest/api/Entity.md#process)
receive `[]`) and no updater function. Rows that share a pk merge in list order, without
[Entity.shouldReorder()](https://dataclient.io/rest/api/Entity.md#shouldreorder). Use this instead of calling `set()` once per row, such as when
[batching high-frequency stream updates](https://dataclient.io/vue/concepts/managers.md#batching).

### setResponse(endpoint, ...args, response) {#setResponse}

Stores `response` in cache for given [Endpoint](https://dataclient.io/rest/api/Endpoint.md) and args.

Components suspending on this [Endpoint](https://dataclient.io/rest/api/Endpoint.md) and args resolve. Existing data for that Endpoint and args is updated; entities merge with their stored fields.

```ts
const ctrl = useController();
let websocket: WebSocket;

onMounted(() => {
  websocket = new WebSocket(url);

  websocket.onmessage = event =>
    ctrl.setResponse(
      EndpointLookup[event.endpoint],
      ...event.args,
      event.data,
    );
});

onUnmounted(() => websocket.close());
```

This is a proof of concept in Vue. A [Manager websockets implementation](https://dataclient.io/vue/concepts/managers.md#data-stream)
is more robust.

### setError(endpoint, ...args, error) {#setError}

Stores `error` as the result of the [Endpoint](https://dataclient.io/rest/api/Endpoint.md) and args.

### resolve(endpoint, { args, response, fetchedAt, error }) {#resolve}

Resolves a specific fetch, storing the `response` in cache.

Like [setResponse](#setResponse), but `fetchedAt` ties the response to one fetch, so that fetch's optimistic update is
removed.

[NetworkManager](https://dataclient.io/vue/api/NetworkManager.md) uses it. Use it when a Manager processes fetch requests.

Pass the fetch action's `action.meta.fetchedAt` as `fetchedAt`. Then the store drops responses to fetches started before
[resetEntireStore()](#resetEntireStore), and an old response doesn't settle a newer fetch of the same key.

### subscribe(endpoint, ...args) {#subscribe}

Adds a subscription to the [Endpoint](https://dataclient.io/rest/api/Endpoint.md) and args. Each call increments its subscriber count.

[useSubscription](https://dataclient.io/vue/api/useSubscription.md) and [useLive](https://dataclient.io/vue/api/useLive.md) call this on mount.

Custom composables can call it to subscribe based on other conditions.

```ts
const controller = useController();

// args can be a ref, computed or getter; this re-runs when it changes
watchEffect(onCleanup => {
  const currentArgs = toValue(args);
  controller.subscribe(endpoint, ...currentArgs);
  onCleanup(() => controller.unsubscribe(endpoint, ...currentArgs));
});
```

### unsubscribe(endpoint, ...args) {#unsubscribe}

Removes a subscription to the [Endpoint](https://dataclient.io/rest/api/Endpoint.md) and args. Each call decrements its subscriber count; at
0, automatic updates stop.

[useSubscription](https://dataclient.io/vue/api/useSubscription.md) and [useLive](https://dataclient.io/vue/api/useLive.md) call this on unmount.

## Data Access

### get(schema, ...args, state) {#get}

Looks up any [Queryable](https://dataclient.io/rest/api/schema.md#queryable) [Schema](https://dataclient.io/rest/api/schema.md#schema-overview) in `state`.

#### Example

[useQuery](https://dataclient.io/vue/api/useQuery.md) builds on it, and [Managers](https://dataclient.io/vue/api/Manager.md) can use it to read the store safely.

In components, [useQuery()](https://dataclient.io/vue/api/useQuery.md) keeps the result reactive. Event handlers read its current value:

```ts
const props = defineProps<{ id: string }>();
const ctrl = useController();
const todo = useQuery(Todo, () => ({ id: props.id }));

const toggle = () => {
  if (!todo.value) return;
  ctrl.set(
    Todo,
    { id: props.id },
    { id: props.id, completed: !todo.value.completed },
  );
};
```

### getResponse(endpoint, ...args, state) {#getResponse}

```ts title="returns"
{
  data: EndpointDataNullable<E>;
  expiryStatus: ExpiryStatus;
  expiresAt: number;
}
```

Gets the response for an endpoint and args from the given `state`.

#### data

The denormalized response. Every member keeps the same reference while its data is unchanged. Its type is [EndpointDataNullable](https://dataclient.io/rest/api/Endpoint.md#endpointdata).

#### [expiryStatus](https://dataclient.io/vue/concepts/expiry-policy.md#expiry-status)

```ts
export enum ExpiryStatus {
  Invalid = 1,
  InvalidIfStale,
  Valid,
}
```

##### Valid

- Will never suspend.
- Might fetch if data is stale

##### InvalidIfStale

- Will suspend if data is stale.
- Might fetch if data is stale

##### Invalid

- Will always suspend during setup; mounted components [keep their current data](https://dataclient.io/vue/concepts/expiry-policy.md#invalidate) until the refetch resolves
- Will always fetch

#### expiresAt

When the data expires, as a timestamp. Compare it to `Date.now()`.

#### Example

[useCache](https://dataclient.io/vue/api/useCache.md) and [useSuspense](https://dataclient.io/vue/api/useSuspense.md) build on it. [Managers](https://dataclient.io/vue/api/Manager.md) can use it to look up a
response in the given state.

In components, [useCache()](https://dataclient.io/vue/api/useCache.md) and [useSuspense()](https://dataclient.io/vue/api/useSuspense.md) keep the result reactive. Event
handlers read their current value.

```tsx title="MyManager.ts"
import {
  type Manager,
  type Middleware,
  actionTypes,
} from '@data-client/vue';

export default class MyManager implements Manager {
  declare protected websocket: WebSocket;

  middleware: Middleware = controller => {
    return next => async action => {
      if (action.type === actionTypes.FETCH) {
        console.log('The existing response of the requested fetch');
        console.log(
          controller.getResponse(
            action.endpoint,
            ...action.args,
            controller.getState(),
          ).data,
        );
      }
      next(action);
    };
  };

  cleanup() {
    this.websocket.close();
  }
}
```

### getError(endpoint, ...args, state) {#getError}

Gets the error for an endpoint and args, or `undefined` if there is none.

### snapshot(state, fetchedAt) {#snapshot}

Returns a [Snapshot](https://dataclient.io/vue/api/Snapshot.md).

### getState() {#getState}

Gets the internal state of Reactive Data Client that has _already been [committed](https://react.dev/learn/render-and-commit#step-3-react-commits-changes-to-the-dom)_.

> **Warning**
>
> Use it only outside components: in [Managers](https://dataclient.io/vue/api/Manager.md), or in code like router loaders.
>
> Using getState() in a `computed()` or template won't update when the store changes. Use
> [useQuery()](https://dataclient.io/vue/api/useQuery.md) or [useCache()](https://dataclient.io/vue/api/useCache.md) there instead.

To act on a mutation's result, use the value `fetch()` resolves with instead of `getState()`. A
[mutation](#endpointsideeffect) resolves _before_ the store is updated, so `getState()` doesn't have its response yet.
The resolved value is the denormalized response.

```html title="UpdatePost.vue"
<script setup lang="ts">
  import { useController } from '@data-client/vue';
  import { useRouter } from 'vue-router';
  import { PostResource } from './PostResource';

  const props = defineProps<{ id: string }>();
  const ctrl = useController();
  const router = useRouter();

  const handleSubmit = async (e: Event) => {
    const post = await ctrl.fetch(
      PostResource.update,
      { id: props.id },
      new FormData(e.target as HTMLFormElement),
    );
    router.push(`/posts/${post.id}`);
  };
</script>

<template>
  <form @submit.prevent="handleSubmit"><!-- ... --></form>
</template>
```
