# The interface

> How forms, server actions, middleware, the database and Zod schemas interface with one another, the reactive index that keeps every view in sync, providers, table forms and queries.

Source: https://asasvirtuais.com/docs/interface

The interface is how the parts of an asasvirtuais app connect: forms, server actions, table middleware, the database
and Zod schemas all interface with one another through the same five operations, `find`, `list`, `create`, `update`
and `remove`, typed by the schema. Their results land in a reactive index, and every view of a table follows it. Most
of an app is forms on top of tables.

## Schema

Each table has a `readable` schema (what the database returns) and a `writable` schema (what a user may send).

```ts
// packages/todos/schema.ts
import z from 'zod'

export const readable = z.object({ id: z.string(), title: z.string(), done: z.boolean(), project: z.string() })
export const writable = readable.pick({ title: true, done: true, project: true })
export const schema = { readable, writable }
```

```ts
// app/schema.ts
export const schema = { projects, todos }
```

## The interface file

`app/actions.ts` exposes the database to the forms. Until the [table middleware](https://asasvirtuais.com/docs/middleware.md) is written, it
passes straight to the raw interface in `app/db.ts`:

```ts
// app/actions.ts
'use server'
import { action } from '@/lib/action'
import { db } from './db'

export const find = action(db.find)
export const list = action(db.list)
export const create = action(db.create)
export const update = action(db.update)
export const remove = action(db.remove)
```

Each method receives the `table` it was called for, along with `{ id }`, `{ query }`, `{ data }` or `{ id, data }`,
and works on that table only. The row it returns is what lands in the index.

## Errors

Next.js hides the message of an error a server action throws in production. So server actions catch it and return
`{ error: message }`, and the client throws it again so the forms can show it:

```ts
// lib/action.ts
import { unstable_rethrow } from 'next/navigation'

type Failure = { error: string }

export function action<A extends any[], R>(fn: (...args: A) => Promise<R>) {
  return async (...args: A): Promise<R | Failure> => {
    try { return await fn(...args) }
    catch (error) { unstable_rethrow(error); return { error: (error as Error).message } }
  }
}

export function ok<R>(result: R | Failure): R {
  if (result && typeof result === 'object' && 'error' in result) throw new Error(result.error)
  return result as R
}

export function unwrap<T extends Record<string, (...args: any[]) => Promise<any>>>(actions: T) {
  return Object.fromEntries(
    Object.entries(actions).map(([name, fn]) => [name, async (...args: any[]) => ok(await fn(...args))])
  ) as { [K in keyof T]: (...args: Parameters<T[K]>) => Promise<Exclude<Awaited<ReturnType<T[K]>>, Failure>> }
}
```

## Providers and hooks

```tsx
// app/providers.tsx
'use client'
import { InterfaceProvider } from 'asasvirtuais/context'
import { unwrap } from '@/lib/action'
import * as actions from './actions'

const appInterface = unwrap(actions)

export default function AppProviders({ children }: { children: React.ReactNode }) {
  return <InterfaceProvider {...appInterface}>{children}</InterfaceProvider>
}
```

Each table gets a provider and hooks in its package:

```tsx
// packages/todos/hooks.tsx + providers.tsx
export const useTodos = () => useTable('todos', schema)
export const useTodo = () => useSingle(schema, 'todos')

export function TodosProvider({ children, asAbove }: React.PropsWithChildren<Pick<TableProviderProps<typeof schema>, 'asAbove'>>) {
  return <TableProvider table='todos' schema={schema} asAbove={asAbove}>{children}</TableProvider>
}

export function TodoProvider({ id, children }: { id: string, children: React.ReactNode }) {
  return <SingleProvider id={id} table='todos' schema={schema}>{children}</SingleProvider>
}
```

Pages are Server Components. They fetch the rows their components show and hand them to the table:

```tsx
// app/todos/page.tsx
export default async function TodosPage() {
  const todos = ok(await list({ table: 'todos', query: { done: false } }))
  return (
    <TodosProvider asAbove={index(todos)}>
      <Todos />
    </TodosProvider>
  )
}
```

`asAbove` is the index the table starts with: the rows keyed by id. New server rows passed to it later
(`router.refresh()`) merge in.

## One record: SingleProvider

`SingleProvider` reads a row from the table's index, fetches it only if it's missing, and follows the index.
Components under it read it with `useSingle` (or your `useTodo()` hook) instead of receiving it as props.

It comes in two implementations with the same behavior:

- **`asasvirtuais/registry`** (the default) keeps every record by table, so nested providers of different tables all
  stay readable: under a `ProjectProvider` and a `TodoProvider`, both `useSingle(schema, 'projects')` and
  `useSingle(schema, 'todos')` work.
- **`asasvirtuais/single`** is a plain React context: `useSingle(schema)` takes no table, and a nested provider
  replaces the one above it.

`SingleProvider` always renders its children. To render nothing until the record exists, use its render prop:

```tsx
<SingleProvider id={id} table='todos' schema={schema}>
  {({ single }) => single ? <TodoItem /> : null}
</SingleProvider>
```

## Table forms

```tsx
// packages/todos/forms.tsx
export function CreateTodo() {
  return (
    <CreateForm table='todos' schema={schema} defaults={{ title: '', done: false }}>
      {todo => (
        <form onSubmit={todo.submit}>
          <TitleField />
          <button type='submit' disabled={todo.loading}>Create todo</button>
        </form>
      )}
    </CreateForm>
  )
}

// one column, one click
export function ToggleTodo() {
  const { single } = useTodo()
  return (
    <UpdateForm table='todos' schema={schema} id={single.id}>
      {toggle => (
        <input type='checkbox' checked={single.done} disabled={toggle.loading}
          onChange={() => toggle.callback({ done: !single.done })} />
      )}
    </UpdateForm>
  )
}

export function DeleteTodo() {
  const { single } = useTodo()
  const { remove } = useTodos()
  return (
    <ActionProvider action={remove.trigger} params={{ id: single.id }}>
      {del => <button onClick={del.submit} disabled={del.loading}>Delete todo</button>}
    </ActionProvider>
  )
}
```

`UpdateForm` sends only the fields in its state (`defaults` plus what `setField` changed). Table forms take
`onSuccess`, which runs with the row returned.

## Listing

The page provides the rows; a list reads the table's `array`, which follows every operation, and filters it. Wrap
each item in its `SingleProvider` so it stays in sync:

```tsx
export function Todos() {
  const { array } = useTodos()
  return array.filter(t => !t.done).map(t => <TodoProvider key={t.id} id={t.id}><TodoItem /></TodoProvider>)
}
```

`FilterForm` (and `list.trigger(...)`) fetch from the client: for what the user asks for while on the page, such as a
search or the next page of results.

## Queries

`list` queries are FeathersJS-style:

| Kind | Operators |
|---|---|
| Field match | `{ done: false }` |
| Comparison | `$ne $lt $lte $gt $gte` |
| Membership | `$in $nin` |
| Logic | `$or $and` |
| Paging and shape | `$limit $skip $sort $select` |

```ts
list({ table: 'todos', query: { done: false, $sort: { createdAt: -1 }, $limit: 20 } })
```

## Next

- [Server code](https://asasvirtuais.com/docs/server-code.md): what doesn't go through the interface
- [Table middleware](https://asasvirtuais.com/docs/middleware.md): authorization
