# Use with Effect UI (https://effetch.monarcode.dev/docs/effect-ui)

Effect UI, the `effect/ui` modules in Effect 4.2 and later, loads a
component's data with queries and changes it with Commands. Both run an
Effect, so an Effetch call fits either one as it is, with no adapter. What
they need from you is two schemas, one for what the call returns and one for
how it fails, because a page rendered on the server sends both to the
browser. This page shows where each schema comes from, and what to change
when the page is public.

Effect marks Effect UI as unstable, so its API can change in a minor Effect
release. Effetch itself works with Effect 4.0 and later, and only Effect UI
needs 4.2.

## Read a call in a query

A query takes its `success` schema from the endpoint's `output`, and its
`error` schema from [`Fetch.errorCodec`](https://effetch.monarcode.dev/docs/errors/across-the-wire). Its
body is the call. The following module defines a client and an endpoint, a
query that reads a todo, and a page that shows the todo or why it failed:

```ts
import * as Effect from "effect/Effect";
import * as AsyncResult from "effect/reactivity/AsyncResult";
import * as Schema from "effect/Schema";
import { Component, Query } from "effect/ui";
import { Html } from "effect/ui/html";

import { Fetch } from "@monarcode/effetch";
import { TimeoutError, retry, timeout } from "@monarcode/effetch/plugins";

class ApiProblem extends Schema.Class<ApiProblem>("ApiProblem")({
  code: Schema.String,
}) {}

class TodoNotFound extends Schema.TaggedError<TodoNotFound>()("TodoNotFound", {
  id: Schema.String,
}) {}

const Todo = Schema.Struct({ id: Schema.Finite, title: Schema.String });

class Api extends Fetch.Service<Api>()("Api", {
  baseUrl: "/api",
  defaultError: ApiProblem,
  plugins: [retry(), timeout({ duration: "5 seconds" })],
}) {}

const getTodo = Fetch.endpoint("GET /todos/:id", {
  output: Todo,
  statusErrors: { 404: TodoNotFound },
});

class Todos extends Fetch.Endpoints<Todos>()("Todos", Api, { get: getTodo }) {}

/** The codec for a call's errors on `Api`, for every query and Command. */
const apiErrors = <S extends Fetch.ErrorCodecSource>(source: S) =>
  Fetch.errorCodec(source, {
    client: Api,
    errors: [TimeoutError],
    redact: true,
  });

export class GetTodo extends Query.Service<GetTodo>()("todos/GetTodo", {
  args: { id: Schema.String },
  success: getTodo.output,
  error: apiErrors(getTodo),
  staleTime: "1 minute",
}) {
  static readonly layer = this.toLayer(
    Effect.gen(function* () {
      const todos = yield* Todos;
      return ({ id }) => todos.get({ params: { id } });
    }),
  );
}

const TodoPageNoDeps = Html.component({
  name: "TodoPage",
  props: Schema.Struct({ id: Schema.String }),
  model: Schema.Struct({}),
  message: Schema.Never,
  queries: {
    todo: { query: GetTodo, args: ({ props }) => ({ id: props.id }) },
  },
}).make({
  init: () => ({}),
  update: ($) => $.model,
  view: (h) =>
    AsyncResult.matchWithError(h.queries.todo, {
      onInitial: () => h.p("Loading…"),
      onError: (error) => {
        switch (error._tag) {
          case "TodoNotFound":
            return h.p(`There's no todo ${error.id}.`);
          case "HttpError":
            return h.p(error.body?.code ?? `HTTP ${error.status}`);
          case "DecodeError":
            return h.p("The todos came back in a shape this page can't read.");
          case "NetworkError":
          case "TimeoutError":
            return h.p("The todos can't be reached.");
        }
      },
      onDefect: () => h.p("Something went wrong."),
      onSuccess: ({ value: todo }) => h.h1(todo.title),
    }),
});

export const TodoPage = TodoPageNoDeps.pipe(Component.provide(GetTodo.layer));
```

The parts that come from Effetch:

- **`success: getTodo.output`** is the schema the call decodes its response
  with. A bound endpoint, such as `Todos`'s `get`, has the same `output`.
- **`apiErrors`** builds the `error` schema. It names the client, whose
  `defaultError` types `HttpError`'s `body`, and the errors the client's
  plugins add, here `TimeoutError`, which no endpoint or client lists.
  Leave one out and the query's `toLayer` doesn't compile, and the message
  names the missing error. With one helper per client, the list lives next
  to the plugins, and adding a plugin means changing one line.
- **The query's `args`** stay in the page's terms, `{ id }`, and the body
  turns them into the call's, `{ params: { id } }`.

In the view, each error has its type, in the browser as on the server.
`TodoNotFound` arrives as an instance of its class, so `instanceof` works
too. `HttpError`'s `body` is an `ApiProblem`, or `undefined` when the
response didn't match it, so read it with `?.`. The view reads `status` and
`body`, not `message`, for a reason
[Render what both sides have](https://effetch.monarcode.dev/docs/effect-ui#render-what-both-sides-have) explains.

`TodoPage` still needs `Todos` and an `HttpClient`. Provide the platform's
`HttpClient` where the app starts, and `Todos.layer` with `Api.layer` to
the page or to the app, as you would for any other service.

Effect UI's query cache doesn't retry a failed query. The client's `retry`
plugin does, inside the call.

## Run a call from a Command

A Command changes data, and the same two schemas describe its result. Give
`make` its args, and map both outcomes with `Command.match` where you issue
it:

```ts
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import { Command } from "effect/ui";

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

class Api extends Fetch.Service<Api>()("Api", { baseUrl: "/api" }) {}

const Todo = Schema.Struct({ id: Schema.Finite, title: Schema.String });

const createTodo = Fetch.endpoint("POST /todos", {
  input: Schema.Struct({ title: Schema.String }),
  output: Todo,
});

class Todos extends Fetch.Endpoints<Todos>()("Todos", Api, {
  create: createTodo,
}) {}

export class CreateTodo extends Command.Service<CreateTodo>()(
  "todos/CreateTodo",
  {
    args: { title: Schema.String },
    success: createTodo.output,
    error: Fetch.errorCodec(createTodo, { client: Api }),
  },
) {
  static readonly layer = this.toLayer(
    Effect.gen(function* () {
      const todos = yield* Todos;
      return ({ title }) => todos.create({ body: { title } });
    }),
  );
}

// In a component's `update`, with its own messages:
export const create = (title: string) =>
  CreateTodo.make({ title }).pipe(
    Command.match({
      onSuccess: (todo) => `Added ${todo.title}`,
      onFailure: (error) => `Couldn't add it (${error._tag})`,
    }),
  );
```

In a component, `onSuccess` and `onFailure` return that component's
messages, and `$.run(create(title))` issues it. Commands only run in the
browser, so their errors don't go in the page.

## Render on the server

A server render runs the page's queries, then writes each settled query
into the page's HTML, so the browser adopts it without fetching it again.
That includes the queries that failed: each error goes in the page as its
query's `error` schema encodes it, where anyone who opens the page source
can read it.

By default, `Fetch.errorCodec` sends what an error carries, for an RPC
client you trust. On a public page, that can show more than you mean to:

```json
{
  "_tag": "HttpError",
  "method": "GET",
  "url": "http://todos.internal:8080/api/todos/7",
  "status": 500,
  "text": "{\"code\":\"db_down\",\"stack\":\"at db.ts:12\"}"
}
```

The URL names the host your server called, which can be an internal one,
and `text` is the response as the backend sent it, with fields your error
schema doesn't declare, such as `stack`. With `redact: true`, as `apiErrors`
passes, the same error goes as:

```json
{
  "_tag": "HttpError",
  "method": "GET",
  "url": "/api/todos/7",
  "status": 500,
  "body": { "code": "db_down" }
}
```

What `redact` changes:

| Field                       | Without `redact`         | With `redact: true`                     |
| --------------------------- | ------------------------ | --------------------------------------- |
| Every error's `url`         | The full URL             | The path, without the scheme and host   |
| `HttpError`'s body          | `text`, the raw response | `body`, as your error schema encodes it |
| A `DecodeError`'s `message` | Can quote the response   | A fixed message                         |

A struct or a class, such as `ApiProblem`, sends only the fields it
declares. A schema that takes any JSON, such as `Schema.Unknown`, sends all
of it, and without an error schema no body is sent. `HttpError`'s `body`
comes back typed in the browser either way, and with `redact` its `text` is
that body as JSON.

The URLs that change are those of `HttpError`, `NetworkError`, `DecodeError`
and a `TimeoutError` given in `errors`. Your `statusErrors` errors send
their own fields either way. `redact` needs Effetch 0.1.1 or later on the
side that decodes, the browser here. For the full list of what's sent, see
[Send errors across the wire](https://effetch.monarcode.dev/docs/errors/across-the-wire#whats-sent).

When the browser shouldn't see an error at all, catch it in the query's
body and fail with an error of your own, or answer the status with one of
your [`statusErrors`](https://effetch.monarcode.dev/docs/errors/status-errors), which sends only its own
fields.

### Render what both sides have

`redact` changes what's written into the page's state, not the error the
server has. The server renders the page's HTML from its own error, with
the full URL and the response, and the browser hydrates it with the error
it decoded. So a view that renders `error.message` puts
`GET http://todos.internal:8080/api/todos/7: HTTP 500` in the HTML, and the
browser, whose error has only the path, renders something else and builds
those nodes again.

Render the fields that are the same on both sides: `_tag`, `method`,
`status`, and `body` when the call has an error schema, as `ApiProblem` is
here. Leave out each error's `url` and `message`, and an `HttpError`'s
`text`. Without an error schema, leave out `body` too: the server's is the
whole parsed response, and `redact` sends none. A test with `ssr`, as in
[Test the pages](https://effetch.monarcode.dev/docs/effect-ui#test-the-pages), fails when a view renders one of them,
with a message that the client rebuilt the server's nodes.

### Call your own API from the server

A client with a relative `baseUrl`, such as `"/api"`, calls the page's own
origin in the browser. On the server there's no page to resolve it
against, so give the server's `HttpClient` the origin:

```ts
import * as Effect from "effect/Effect";
import * as FetchHttpClient from "effect/http/FetchHttpClient";
import * as HttpClient from "effect/http/HttpClient";
import * as HttpClientRequest from "effect/http/HttpClientRequest";
import * as Layer from "effect/Layer";

export const ServerHttpClient = Layer.effect(
  HttpClient.HttpClient,
  Effect.map(
    HttpClient.HttpClient,
    HttpClient.mapRequest(
      HttpClientRequest.prependUrl("http://localhost:3000"),
    ),
  ),
).pipe(Layer.provide(FetchHttpClient.layer));
```

Provide it where the server renders, in place of the browser's
`FetchHttpClient.layer`. The URLs your calls fail with are then absolute on
the server, which is one more reason to `redact` what the page ships.

`HtmlServerHttp.layerHttp` builds the services you give it once, and every
request shares them. For a service that belongs to one request, such as the
signed-in user's cookie on each call, render with `HtmlServer.renderToHtml`
in your own route handler, and build the client's layers there.

### Fit retries into the render's budget

A server render waits for its queries up to its `budget`. A query that's
still loading then, a retried call included, renders its loading state, and
the browser loads it after hydration. Give the budget room for the `retry`
plugin's waits, or the page renders a loading state that a second attempt
would have filled.

## Test the pages

`FetchTest.layer` is an `HttpClient`, so it can stand in for the platform's
under Effect UI's test tools, and your queries, endpoints and client run as
they are. The following test renders `TodoPage` on the server, hydrates it
in a fresh document, and checks the error the page shipped:

```ts
// @vitest-environment happy-dom
import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as AsyncResult from "effect/reactivity/AsyncResult";
import * as Schema from "effect/Schema";
import { Component, Query } from "effect/ui";
import { Html } from "effect/ui/html";
import { ssr } from "effect/ui/html/testing";
import { TestHost } from "effect/ui/testing";

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

class Api extends Fetch.Service<Api>()("Api", {
  baseUrl: "https://todos.internal:8080",
}) {}

const getTodo = Fetch.endpoint("GET /todos/:id", {
  output: Schema.Struct({ id: Schema.Finite, title: Schema.String }),
});

class Todos extends Fetch.Endpoints<Todos>()("Todos", Api, { get: getTodo }) {}

class GetTodo extends Query.Service<GetTodo>()("todos/GetTodo", {
  args: { id: Schema.String },
  success: getTodo.output,
  error: Fetch.errorCodec(getTodo, { client: Api, redact: true }),
  staleTime: "1 minute",
}) {
  static readonly layer = this.toLayer(
    Effect.gen(function* () {
      const todos = yield* Todos;
      return ({ id }) => todos.get({ params: { id } });
    }),
  );
}

const TodoPage = Html.component({
  name: "TodoPage",
  props: Schema.Struct({ id: Schema.String }),
  model: Schema.Struct({}),
  message: Schema.Never,
  queries: {
    todo: { query: GetTodo, args: ({ props }) => ({ id: props.id }) },
  },
})
  .make({
    init: () => ({}),
    update: ($) => $.model,
    view: (h) =>
      AsyncResult.match(h.queries.todo, {
        onInitial: () => h.p("Loading…"),
        onFailure: () => h.p("Couldn't load the todo."),
        onSuccess: ({ value: todo }) => h.h1(todo.title),
      }),
  })
  .pipe(Component.provide(GetTodo.layer));

const Backend = FetchTest.layer([
  FetchTest.respond(getTodo, () =>
    Effect.succeed(FetchTest.reply(500, { code: "db_down" })),
  ),
]);

it.effect("ships a failed todo without the raw response", () =>
  Effect.gen(function* () {
    // Renders on the server, then hydrates in a fresh document. It fails
    // when the browser fetches what the server shipped.
    const result = yield* ssr(TodoPage, { id: "7" });
    assert.include(result.html, "Couldn't load the todo.");
    const shipped = JSON.stringify(result.state["~query"]);
    assert.include(shipped, '"url":"/todos/7"');
    assert.notInclude(shipped, "todos.internal");
    assert.notInclude(shipped, '"text"');
  }).pipe(
    Effect.scoped,
    Effect.provide(
      Layer.mergeAll(
        Todos.layer.pipe(Layer.provide(Api.layer), Layer.provide(Backend)),
        TestHost.layer(),
      ),
    ),
  ),
);
```

Two things about time in these tests:

- `it.effect` runs on Effect's test clock, which only moves when the test
  moves it. `ssr` moves it, up to its `budget`, 500 milliseconds unless you
  give one. A client with the `retry` plugin waits between attempts, so pass
  `ssr` the budget your server renders with.
- A Play (`HtmlPlay.make`) doesn't move the clock. After an action whose
  call is retried, move it yourself with `TestClock.adjust`, from
  `effect/testing/TestClock`.

## See it in an app

The repository's
[`examples/store-ui`](https://github.com/monarcode/effetch/tree/main/examples/store-ui)
is the [`store`](https://effetch.monarcode.dev/docs/structuring-an-app) example's modules behind an Effect
UI app, rendered on the server with Vite and hydrated in the browser. Its
queries use one `storeErrors` helper with `redact: true`, a 404 reaches the
product page as `ProductNotFound`, and buying the cheapest product is a
Command that fails with the workflow's errors and the calls'. Its tests
render each page with `ssr` and drive the purchase with a Play, against
`FetchTest`. Run it with `pnpm example store-ui`.

## What's next

- [Send errors across the wire](https://effetch.monarcode.dev/docs/errors/across-the-wire): see what
  `Fetch.errorCodec` sends for each error, with `redact` and without.
- [Test with a fake backend](https://effetch.monarcode.dev/docs/testing): answer your endpoints with
  `FetchTest`.
- [Structure an app](https://effetch.monarcode.dev/docs/structuring-an-app): lay out the modules a UI
  reads from.