From 64df75d53fe96a5ec999b22748f5c47560fd5a6a Mon Sep 17 00:00:00 2001 From: monarcode Date: Mon, 23 Nov 2026 06:14:43 +0100 Subject: [PATCH] docs: move the guides from the README to the docs site --- AGENTS.md | 4 + CHANGELOG.md | 16 + README.md | 3206 +---------------- package.json | 2 +- scripts/smoke.sh | 3 +- site/content/docs/(latest)/calls/body.mdx | 67 + .../docs/(latest)/calls/http-client.mdx | 42 +- site/content/docs/(latest)/calls/index.mdx | 19 + site/content/docs/(latest)/calls/options.mdx | 21 + .../docs/(latest)/calls/parameters.mdx | 52 + .../content/docs/(latest)/calls/responses.mdx | 129 + site/content/docs/(latest)/calls/uploads.mdx | 170 + .../docs/(latest)/clients/configuration.mdx | 50 + .../content/docs/(latest)/clients/derived.mdx | 41 + site/content/docs/(latest)/clients/index.mdx | 75 + .../docs/(latest)/clients/providing.mdx | 70 + .../docs/(latest)/clients/service-or-make.mdx | 78 + .../docs/(latest)/coming-from-axios-or-ky.mdx | 23 + .../docs/(latest)/endpoints/calling.mdx | 132 +- .../docs/(latest)/endpoints/defining.mdx | 80 + .../content/docs/(latest)/endpoints/index.mdx | 83 + .../content/docs/(latest)/endpoints/meta.json | 2 +- .../docs/(latest)/endpoints/services.mdx | 105 +- .../docs/(latest)/endpoints/typed-query.mdx | 78 +- site/content/docs/(latest)/endpoints/urls.mdx | 67 +- .../content/docs/(latest)/errors/catching.mdx | 94 + .../docs/(latest)/errors/error-bodies.mdx | 29 + site/content/docs/(latest)/errors/index.mdx | 35 + .../(latest)/errors/logging-and-defects.mdx | 29 + .../docs/(latest)/errors/status-errors.mdx | 161 + site/content/docs/(latest)/examples.mdx | 33 + .../content/docs/(latest)/getting-started.mdx | 120 + site/content/docs/(latest)/index.mdx | 5 +- site/content/docs/(latest)/installation.mdx | 6 +- site/content/docs/(latest)/pagination.mdx | 109 + site/content/docs/(latest)/platforms.mdx | 59 + .../docs/(latest)/plugins/console-logging.mdx | 159 +- site/content/docs/(latest)/plugins/index.mdx | 82 +- site/content/docs/(latest)/plugins/order.mdx | 28 +- .../docs/(latest)/plugins/per-call.mdx | 52 + .../content/docs/(latest)/plugins/recipes.mdx | 98 + .../docs/(latest)/plugins/retry-after.mdx | 46 + .../docs/(latest)/plugins/token-refresh.mdx | 71 +- .../content/docs/(latest)/plugins/writing.mdx | 149 + .../docs/(latest)/reference/compatibility.mdx | 4 - .../docs/(latest)/reference/fetch-test.mdx | 4 - .../content/docs/(latest)/reference/fetch.mdx | 4 - .../content/docs/(latest)/reference/index.mdx | 92 +- .../docs/(latest)/reference/limitations.mdx | 33 + .../content/docs/(latest)/reference/meta.json | 9 +- .../docs/(latest)/reference/plugins.mdx | 4 - site/content/docs/(latest)/streaming.mdx | 200 + .../docs/(latest)/structuring-an-app.mdx | 238 ++ site/content/docs/(latest)/testing/errors.mdx | 92 + .../docs/(latest)/testing/http-client.mdx | 62 +- site/content/docs/(latest)/testing/index.mdx | 136 + .../docs/(latest)/testing/requests.mdx | 78 + .../content/docs/(latest)/testing/streams.mdx | 58 +- site/content/docs/(latest)/upgrading.mdx | 79 + site/src/components/mdx.tsx | 3 + 60 files changed, 3866 insertions(+), 3210 deletions(-) delete mode 100644 site/content/docs/(latest)/reference/compatibility.mdx delete mode 100644 site/content/docs/(latest)/reference/fetch-test.mdx delete mode 100644 site/content/docs/(latest)/reference/fetch.mdx delete mode 100644 site/content/docs/(latest)/reference/plugins.mdx diff --git a/AGENTS.md b/AGENTS.md index 832a375..7fa5d19 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -54,6 +54,10 @@ to static files. It's a package in the pnpm workspace and isn't published. skips it. It compiles `ts` only, so a JSX example needs the check extended first. - Pages are `.mdx` only: the site and the docs check read no other files. +- The guides live on the site, once. The README is an overview that links + to them, so when a feature changes, update its page, and the README only + if its quick start or links change. Link between pages with root-relative + paths (`/docs/errors/status-errors`). - `pnpm run check` doesn't build the site. After changing `site/`, run `pnpm run build:site`, which prerenders the site into `site/dist/client`. `pnpm --dir site run dev` serves it while you write. diff --git a/CHANGELOG.md b/CHANGELOG.md index 8616069..13292b4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,22 @@ All notable changes to `@monarcode/effetch`, newest first. +## Unreleased + +### Added + +- Documentation site at [effetch.pages.dev/docs](https://effetch.pages.dev/docs), + with a page for each guide that was in the README, and search. The + package's `homepage` points to it. + +### Changed + +- The README is now an overview: what Effetch is, how to install it, a + quick start and links to the site's guides. The sections that earlier + entries name, such as "Upgrading from 0.1.0-rc.3" and "Uploading files", + are now [Upgrade from 0.1.0-rc.3](https://effetch.pages.dev/docs/upgrading) + and [Upload files](https://effetch.pages.dev/docs/calls/uploads). + ## 0.1.0-rc.4 ### Changed diff --git a/README.md b/README.md index c2c8383..8687d13 100644 --- a/README.md +++ b/README.md @@ -14,12 +14,12 @@ [![license](https://img.shields.io/npm/l/@monarcode/effetch)](./LICENSE) [![Effect](https://img.shields.io/badge/Effect%204-20232a?logo=effect&logoColor=white)](https://effect.website) -[![Browsers](https://img.shields.io/badge/Browsers-20232a?logo=googlechrome&logoColor=white)](#browsers) -[![React Native](https://img.shields.io/badge/React%20Native-20232a?logo=react&logoColor=61dafb)](#react-native) -[![Expo](https://img.shields.io/badge/Expo-20232a?logo=expo&logoColor=white)](#react-native) -[![Node.js](https://img.shields.io/badge/Node.js%2020+-20232a?logo=nodedotjs&logoColor=5fa04e)](#platform-notes) -[![Bun](https://img.shields.io/badge/Bun-20232a?logo=bun&logoColor=fbf0df)](#platform-notes) -[![Deno](https://img.shields.io/badge/Deno-20232a?logo=deno&logoColor=white)](#platform-notes) +[![Browsers](https://img.shields.io/badge/Browsers-20232a?logo=googlechrome&logoColor=white)](https://effetch.pages.dev/docs/platforms#browsers) +[![React Native](https://img.shields.io/badge/React%20Native-20232a?logo=react&logoColor=61dafb)](https://effetch.pages.dev/docs/platforms#react-native) +[![Expo](https://img.shields.io/badge/Expo-20232a?logo=expo&logoColor=white)](https://effetch.pages.dev/docs/platforms#react-native) +[![Node.js](https://img.shields.io/badge/Node.js%2020+-20232a?logo=nodedotjs&logoColor=5fa04e)](https://effetch.pages.dev/docs/platforms) +[![Bun](https://img.shields.io/badge/Bun-20232a?logo=bun&logoColor=fbf0df)](https://effetch.pages.dev/docs/platforms) +[![Deno](https://img.shields.io/badge/Deno-20232a?logo=deno&logoColor=white)](https://effetch.pages.dev/docs/platforms) **Typed HTTP calls for [Effect](https://effect.website), without the boilerplate.** @@ -55,193 +55,12 @@ export const getTodo = (id: number) => > features and fixes, and the [changelog](./CHANGELOG.md) lists anything > that needs a change in your code. -## Contents +## Documentation -- [Why Effetch](#why-effetch) - - [At a glance](#at-a-glance) - - [What you get](#what-you-get) - - [Where it fits](#where-it-fits) -- [Getting started](#getting-started) - - [Install](#install) - - [Importing](#importing) - - [Your first client](#your-first-client) - - [How the pieces fit](#how-the-pieces-fit) -- [Setting up a client](#setting-up-a-client) - - [Declaring a client](#declaring-a-client) - - [Configuration](#configuration) - - [Providing the client](#providing-the-client) - - [A client from another](#a-client-from-another) - - [Fetch.Service or Fetch.make?](#fetchservice-or-fetchmake) -- [Making calls](#making-calls) - - [Methods](#methods) - - [Path and query parameters](#path-and-query-parameters) - - [Sending a body](#sending-a-body) - - [Uploading files](#uploading-files) - - [Reading the response](#reading-the-response) - - [All call options](#all-call-options) - - [When the methods aren't enough](#when-the-methods-arent-enough) -- [Handling errors](#handling-errors) - - [What can go wrong](#what-can-go-wrong) - - [Catching errors](#catching-errors) - - [Typed error bodies](#typed-error-bodies) - - [Errors by status](#errors-by-status) - - [Safe to log](#safe-to-log) - - [Bugs are defects](#bugs-are-defects) -- [Plugins](#plugins) - - [Built-in plugins](#built-in-plugins) - - [Refreshing a token](#refreshing-a-token) - - [Retry-After and a time limit](#retry-after-and-a-time-limit) - - [Console logging](#console-logging) - - [Plugin order](#plugin-order) - - [Changing plugins for one call](#changing-plugins-for-one-call) -- [Endpoints](#endpoints) - - [Why endpoints](#why-endpoints) - - [Defining endpoints](#defining-endpoints) - - [Sharing endpoints as a service](#sharing-endpoints-as-a-service) - - [Calling an endpoint](#calling-an-endpoint) - - [Other ways to bind endpoints](#other-ways-to-bind-endpoints) - - [Typed query parameters](#typed-query-parameters) - - [Building an endpoint's URL](#building-an-endpoints-url) - - [Defaults and overrides](#defaults-and-overrides) - - [Endpoints or methods?](#endpoints-or-methods) -- [Streaming responses](#streaming-responses) - - [Server-Sent Events](#server-sent-events) - - [Newline-delimited JSON](#newline-delimited-json) - - [Stream endpoints](#stream-endpoints) - - [How a stream fails](#how-a-stream-fails) - - [Stopping a stream](#stopping-a-stream) -- [Pagination](#pagination) - - [Cursors in headers](#cursors-in-headers) -- [Writing plugins](#writing-plugins) - - [Your first plugin](#your-first-plugin) - - [Hooks](#hooks) - - [Knowing the route](#knowing-the-route) - - [Example: signing out on a 401](#example-signing-out-on-a-401) - - [Example: a deadline with its own error](#example-a-deadline-with-its-own-error) - - [Tips](#tips) -- [Structuring an app](#structuring-an-app) - - [A small app](#a-small-app) - - [A feature-sliced app](#a-feature-sliced-app) - - [Several backends](#several-backends) -- [Testing](#testing) - - [A fake backend from your endpoints](#a-fake-backend-from-your-endpoints) - - [Errors and other statuses](#errors-and-other-statuses) - - [Stream endpoints in tests](#stream-endpoints-in-tests) - - [Checking what was sent](#checking-what-was-sent) - - [How requests are matched](#how-requests-are-matched) - - [A hand-written HttpClient](#a-hand-written-httpclient) -- [Platform notes](#platform-notes) - - [Browsers](#browsers) - - [React Native](#react-native) -- [Coming from axios or ky](#coming-from-axios-or-ky) -- [Reference](#reference) - - [Limitations](#limitations) - - [API](#api) -- [Examples](#examples) -- [Development](#development) -- [License](#license) +The guides are at +**[effetch.pages.dev/docs](https://effetch.pages.dev/docs)**. -## Why Effetch - -Effect gives you two ways to call an HTTP API, and they sit at opposite -ends: - -- **`HttpClient` is low level.** For every request you build the URL, check - the status and decode the body yourself. -- **`HttpApi` is contract first.** You describe the whole API up front and - share it with the server, which is ideal when you own both sides. - -Most apps sit in between. They call a backend they don't control, such as -their company's REST API or a third-party service, one call at a time. -Effetch is made for that. It's a thin layer over `HttpClient` that gives each -call the types and error handling of a contract, without you having to write -one. - -### At a glance - -Here's the same call written with `HttpClient` alone, and with Effetch: - -```ts -import * as Effect from "effect/Effect"; -import * as HttpClient from "effect/http/HttpClient"; -import * as HttpClientResponse from "effect/http/HttpClientResponse"; -import * as HttpIncomingMessage from "effect/http/HttpIncomingMessage"; -import * as Schema from "effect/Schema"; - -import type { Fetch } from "@monarcode/effetch"; - -declare const api: Fetch.Client; - -const Todo = Schema.Struct({ id: Schema.Finite, title: Schema.String }); - -// With HttpClient alone -export const getTodoByHand = (id: number) => - Effect.gen(function* () { - const client = yield* HttpClient.HttpClient; - const response = yield* client.get( - `https://api.example.com/todos/${encodeURIComponent(id)}`, - ); - const ok = yield* HttpClientResponse.filterStatusOk(response); - return yield* HttpIncomingMessage.schemaBodyJson(Todo)(ok); - }); - -// With Effetch -export const getTodo = (id: number) => - api.get("/todos/:id", { params: { id }, output: Todo }); -``` - -Both send the same request and decode the same response. The Effetch version -also: - -- checks at compile time that every call passes an `id`; -- fails with `NetworkError`, `HttpError` or `DecodeError` rather than - `HttpClientError | SchemaError`, so you can handle each case on its own; -- decodes the API's error body onto `HttpError`, with a schema you give it; -- runs the client's plugins, such as auth, retries, timeouts and logging, on - every call. - -### What you get - -- **Paths that check themselves.** Write `"/users/:id"` and TypeScript asks - for `params: { id }`. No more, no less. -- **Queries from plain objects.** `{ page: 2, tags: ["a", "b"] }` becomes - `?page=2&tags=a&tags=b`, and `undefined` values are left out. -- **Responses you can trust.** Decode the response with a `Schema`, and the - API's error body with another. The schemas' types become the call's types. -- **Errors you can catch by name.** Three tagged errors, `NetworkError`, - `HttpError` and `DecodeError`, plus any your plugins add, all in the type. - Turn statuses into your own errors, such as a `404` into `TodoNotFound`, - with `statusErrors`. -- **Plugins for the repetitive parts.** Auth with token refresh, retries, - timeouts and logging are built in, and your own take a few lines. Any call - can turn a plugin off or adjust it, and TypeScript checks the names and - options. -- **Endpoints.** Save a route like `"GET /users/:id"` with its schemas once, - then call it like a function wherever you need it. Share a module's - endpoints as a service with `Fetch.Endpoints`. -- **Streams and pages.** Read Server-Sent Events and newline-delimited JSON - as an Effect `Stream`, and page through a list with `Fetch.paginate`. -- **Tests without a network.** `FetchTest` makes a typed fake backend from - your endpoints, so tests run the real client with its plugins. -- **Runs anywhere.** There are no platform-specific imports or builds: it targets browsers, - React Native, Node 20+, Bun and Deno. - -### Where it fits - -- Use **Effetch** to call REST and JSON APIs that you don't own, or don't - share code with. -- Use Effect's **`HttpApi`** when you own both the server and the client, - and want them to share one contract. -- Use **`HttpClient`** directly for what Effetch doesn't cover, such as - WebSockets or uploads with progress. Every Effetch client gives you its - own when you need it. - -Coming from axios or ky? [This table](#coming-from-axios-or-ky) maps what -you know to Effetch. - -## Getting started - -### Install +## Install ```bash pnpm add @monarcode/effetch effect @@ -261,76 +80,11 @@ You'll need: - TypeScript 5.4 or newer. With `skipLibCheck: false`, Effect's own declarations need TypeScript 5.7 or newer. -### Importing - -Everything in the main entry is under one export, `Fetch`. Plugins and the -test backend have their own entries: - -```ts -import { Fetch } from "@monarcode/effetch"; -import { bearer, retry } from "@monarcode/effetch/plugins"; -import { FetchTest } from "@monarcode/effetch/test"; - -export const plugins = [bearer({ token: "token" }), retry()]; -export const getTodo = Fetch.endpoint("GET /todos/:id"); -export const Backend = FetchTest.layer([]); -``` - -Your editor offers to add the `Fetch` import as you type it. For types -alone, use `import type { Fetch } from "@monarcode/effetch"`. - -The package also has `@monarcode/effetch/Fetch` and -`@monarcode/effetch/test/FetchTest`: the same exports, without the -namespace, as `effect/Effect` is to `import { Effect } from "effect"`. -TypeScript uses them to name Effetch's types in the `.d.ts` files it emits -for your code. In your own code, import from the main entry. - -#### Upgrading from 0.1.0-rc.3 - -Before 0.1.0-rc.4, the main entry exported each API by name, and you -imported it with `import * as Fetch`. To move a project to the `Fetch` -export, upgrade it, then run the migration in the directory of the -package that depends on Effetch: - -```bash -npx -p @monarcode/effetch effetch-migrate --dry-run -``` - -```bash -npx -p @monarcode/effetch effetch-migrate -``` - -The first command lists the files it would change. The second changes -them. With pnpm, run `pnpm exec effetch-migrate` instead. It makes these -changes: - -- `import * as Fetch from "@monarcode/effetch"` becomes - `import { Fetch } from "@monarcode/effetch"`. -- Named imports, such as `import { HttpError, type Client }`, become - `import { Fetch }`, and each use becomes `Fetch.HttpError` or - `Fetch.Client`. -- `export … from "@monarcode/effetch"` re-exports from - `@monarcode/effetch/Fetch`, and `import("@monarcode/effetch").Client` - types become `import("@monarcode/effetch").Fetch.Client`. -- Code that already imports `Fetch` is left as it is. - -It reads `.ts`, `.tsx`, `.js` and similar files, and uses the project's -own TypeScript. In a git repository it reads the files git sees, so it -skips what `.gitignore` does. Elsewhere, it skips `node_modules`, `dist`, -`build`, `coverage` and hidden directories, and lists the build output it -skipped. Pass paths to choose what it reads, such as -`effetch-migrate src test`. - -It lists, with their lines, what it can't rewrite for you to change by -hand: a dynamic `import()`, a `vi.mock("@monarcode/effetch")`, an import -inside a `declare module` block, and JSDoc comments that use the old -names. It doesn't read Markdown. Afterwards, run your formatter and type -checker. +## Quick start -### Your first client - -Let's fetch a todo from [JSONPlaceholder](https://jsonplaceholder.typicode.com), -a free fake API. This is a complete program you can run: +This program fetches a todo from +[JSONPlaceholder](https://jsonplaceholder.typicode.com), a free fake API, +and decodes it with a schema: ```ts import * as Effect from "effect/Effect"; @@ -368,2911 +122,37 @@ const ApiLive = Api.layer.pipe(Layer.provide(FetchHttpClient.layer)); await Effect.runPromise(program.pipe(Effect.provide(ApiLive))); ``` -Here's what each part does: - -1. **`Todo` describes the response.** Effetch decodes the body with it, so - `todo` is typed, and checked when it arrives. If the API sends something - else, the call fails with a `DecodeError` instead of handing you bad data. -2. **`Api` is your client.** `Fetch.Service` declares it as an Effect - service, with everything its calls have in common: here the base URL, - later the headers, error schemas and plugins. -3. **`api.get` makes the call.** `yield* Api` gives you the client, and the - `:id` in the path is filled in from `params`. -4. **`Api.layer` builds the client.** It needs an `HttpClient` to send the - requests. `FetchHttpClient.layer` uses the global `fetch`. Node's works - too, and in tests you'd use a fake one (see [Testing](#testing)). +`Api` is your client, declared once for the whole app. `api.get` fills in +`:id` from `params`, sends the request and decodes the body with `Todo`. +`Api.layer` builds the client, with the `HttpClient` that sends the +requests. [Getting started](https://effetch.pages.dev/docs/getting-started) +walks through each part. Calling an API from a web page on another origin? Read -[Browsers](#browsers) first. - -### How the pieces fit - -Everything in Effetch builds on four ideas, from the bottom up: - -- **An `HttpClient`** sends requests. It's Effect's, and you choose it when - you run your program: the global `fetch`, Node's, or a fake in tests. -- **A client** is one backend: its base URL, default headers, error schemas - and plugins. You declare it once, with `Fetch.Service`. -- **A call** is one request: a method such as `api.get`, or an - [endpoint](#endpoints) you saved. It returns an Effect, typed by your - schemas, that fails with typed errors. -- **Plugins** wrap every call a client makes, for auth, retries, timeouts - and logging. - -The rest of this guide follows the same order: [setting up a -client](#setting-up-a-client), [making calls](#making-calls) and [handling -errors](#handling-errors), then [plugins](#plugins) and -[endpoints](#endpoints). After those come [streams](#streaming-responses), -[pagination](#pagination), [your own plugins](#writing-plugins), [how to -structure an app](#structuring-an-app) and [testing](#testing). - -> **About the examples.** To stay short, many examples start from -> `declare const api: Fetch.Client`: a client without plugins, like the one -> `yield* Api` gives you when `Api` has none. In your app, get the client with -> `yield* Api`. To type a client in a function signature, use -> `Effect.Success`, which includes your plugins and error -> schemas. Some examples also bind an endpoint inline, with `api.bind`, to -> stay short; in your app, bind endpoints once, with -> [`Fetch.Endpoints`](#sharing-endpoints-as-a-service). Every TypeScript -> example in this README is compiled with the package, so they all match the -> API. - -## Setting up a client - -A client holds everything a backend's calls have in common: where the -backend lives, the headers every request needs, the shape of its errors and -the plugins every call goes through. You declare it once and share it with -the rest of your app. - -### Declaring a client - -`Fetch.Service` declares a client as an Effect service, in one class: - -```ts -import * as Effect from "effect/Effect"; -import * as Schema from "effect/Schema"; - -import { Fetch } from "@monarcode/effetch"; - -const Todo = Schema.Struct({ id: Schema.Finite, title: Schema.String }); - -export class Api extends Fetch.Service()("Api", { - baseUrl: "https://api.example.com", -}) {} - -// Anywhere in your app -export const program = Effect.gen(function* () { - const api = yield* Api; - return yield* api.get("/todos/:id", { params: { id: 1 }, output: Todo }); -}); -``` - -The class gives you three things: - -- **`Api` is the service.** `yield* Api` gives the client, typed from the - config. -- **`Api.layer` builds the client.** It needs an `HttpClient`, plus - whatever the `baseUrl` Effect and the plugins need. Every layer that - depends on it in one layer graph gets the same client. -- **`Api.config` is the config you passed**, frozen. You can read it when - the module loads, before any layer is built, for example to get the - `defaultError` and `statusErrors` schemas. - -A few things worth knowing: - -- **Your client's type is `Effect.Success`.** It includes your - plugins and your `defaultError`. Use it wherever you need to type a - client, such as a function parameter. `Fetch.Client` is the type of a - client without plugins, and yours won't fit it. -- **Calls need nothing from the environment.** The client holds on to the - `HttpClient`, the base URL and any services its plugins need. Its calls - only need the services of their own schemas, if any, so they run anywhere: - in a service, in a query function, or with `Effect.runPromise`. -- **Give each client its own id.** Two classes with the same id are the same - service. `Fetch.isService(value)` tells a class made by `Fetch.Service` - apart from any other value. - -### Configuration - -The config takes the same options as `Fetch.make`. Here's a client with all -of them: - -```ts -import * as Config from "effect/Config"; -import * as Schema from "effect/Schema"; - -import { Fetch } from "@monarcode/effetch"; -import { bearer, logger, retry, timeout } from "@monarcode/effetch/plugins"; - -const ApiError = Schema.Struct({ code: Schema.String, message: Schema.String }); - -class SessionExpired extends Schema.TaggedError()( - "SessionExpired", - { message: Schema.String }, -) {} - -const session: { accessToken?: string } = {}; - -export class Api extends Fetch.Service()("Api", { - baseUrl: Config.String("API_URL"), - headers: { "x-client": "web" }, - defaultError: ApiError, - statusErrors: { 401: SessionExpired }, - plugins: [ - logger(), - retry(), - timeout({ duration: "10 seconds" }), - bearer({ token: () => session.accessToken }), - ], -}) {} -``` - -Every option is optional: - -| Option | What it's for | -| -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `baseUrl` | Where the API lives. It's put in front of every path that isn't a full `http(s)://` URL. Pass a string, or an Effect that's run once when the client is built, such as a `Config`. It can't contain a query string or a fragment. | -| `headers` | Headers sent with every request. A call's header with the same name wins. `content-type` and `content-length` are ignored here, since they come from each body. | -| `defaultError` | A schema for the body of the API's error responses (see [Typed error bodies](#typed-error-bodies)). | -| `statusErrors` | Your own errors for error responses, by status, for every call (see [Errors by status](#errors-by-status)). | -| `plugins` | Behaviour every call goes through, outermost first (see [Plugins](#plugins)). | - -### Providing the client - -`Api.layer` needs an `HttpClient`. Provide one where you run your program, -usually next to the other layers of your app: - -```ts -import * as Effect from "effect/Effect"; -import * as FetchHttpClient from "effect/http/FetchHttpClient"; -import * as Layer from "effect/Layer"; - -import { Fetch } from "@monarcode/effetch"; - -export class Api extends Fetch.Service()("Api", { - baseUrl: "https://api.example.com", -}) {} - -export const ApiLive = Api.layer.pipe(Layer.provide(FetchHttpClient.layer)); - -export const program = Effect.gen(function* () { - const api = yield* Api; - return yield* api.get("/health"); -}); - -export const runnable = program.pipe(Effect.provide(ApiLive)); -``` - -Keeping the `HttpClient` out of `Api.layer` is what lets tests swap in a -fake one. If you'd rather have `Api.layer` provide it too, override it in -the class: - -```ts -import * as FetchHttpClient from "effect/http/FetchHttpClient"; -import * as Layer from "effect/Layer"; - -import { Fetch } from "@monarcode/effetch"; - -export class Api extends Fetch.Service()("Api", { - baseUrl: "https://api.example.com", -}) { - static override readonly layer = super.layer.pipe( - Layer.provide(FetchHttpClient.layer), - ); -} -``` - -An override can need less than the original layer, but not more, and can't -add an error. - -> **Caution:** the override builds the real `HttpClient` into `Api.layer`, -> so a test can no longer swap in a fake one: `FetchTest.layer` provided -> under it is ignored, and requests go to the network. If you test with -> `Api.layer`, keep it as it is and export a separate `ApiLive`, as in the -> first example. - -### A client from another - -For the same client with a different base URL, such as a second API -version, or with one more header, spread the first class's `config` into a -second class. It keeps the plugins, `defaultError` and `statusErrors`, so -its client has the same type: - -```ts -import * as Schema from "effect/Schema"; - -import { Fetch } from "@monarcode/effetch"; -import { retry } from "@monarcode/effetch/plugins"; - -export class Api extends Fetch.Service()("Api", { - baseUrl: "https://api.example.com/v1", - defaultError: Schema.Struct({ code: Schema.String }), - plugins: [retry()], -}) {} - -export class ApiV2 extends Fetch.Service()("ApiV2", { - ...Api.config, - baseUrl: "https://api.example.com/v2", -}) {} -``` - -`Api.config.headers` is replaced, not merged, when you set `headers`: spread -it too, as in `headers: { ...Api.config.headers, "x-client": "web" }`. - -### Fetch.Service or Fetch.make? - -`Fetch.make` is the function underneath `Fetch.Service`: it takes the same -config and returns an Effect that builds the client. Use the class by -default, and reach for `Fetch.make` when the class doesn't fit: - -| Situation | Use | -| --------------------------------------------------------------------------------------- | --------------- | -| An app, with the client shared as a service | `Fetch.Service` | -| A config known when the module loads (a `baseUrl` Effect such as `Config` is fine) | `Fetch.Service` | -| Endpoints shared as a service with [`Fetch.Endpoints`](#sharing-endpoints-as-a-service) | `Fetch.Service` | -| A script, a one-off program, or a quick test | `Fetch.make` | -| A config that comes from an Effect, such as headers read from a service | `Fetch.make` | -| A client made inside your own service's layer, or one per tenant at runtime | `Fetch.make` | - -In a script, use `Fetch.make` inline: - -```ts -import * as Effect from "effect/Effect"; -import * as FetchHttpClient from "effect/http/FetchHttpClient"; - -import { Fetch } from "@monarcode/effetch"; - -const program = Effect.gen(function* () { - const api = yield* Fetch.make({ baseUrl: "https://api.example.com" }); - return yield* api.get("/health"); -}); - -await Effect.runPromise(program.pipe(Effect.provide(FetchHttpClient.layer))); -``` - -When the config itself comes from an Effect, call `Fetch.make` inside that -Effect and declare the service by hand: - -```ts -import * as Context from "effect/Context"; -import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; - -import { Fetch } from "@monarcode/effetch"; - -class Tenant extends Context.Service()( - "Tenant", -) {} - -const makeApi = Effect.gen(function* () { - const tenant = yield* Tenant; - return yield* Fetch.make({ - baseUrl: "https://api.example.com", - headers: { "x-tenant": tenant.id }, - }); -}); - -export class Api extends Context.Service>()( - "Api", -) {} - -export const ApiLive = Layer.effect(Api)(makeApi); -``` - -Both give you the same client, with the same calls and the same types. - -## Making calls - -With a client in hand, every call is one method: the path, an object of -options, and an Effect back. - -### Methods - -A client has a method for each HTTP method: - -- `get`, `head` and `options` send no body. -- `post`, `put`, `patch` and `del` can send one. It's `del` because `delete` - is a reserved word. - -### Path and query parameters - -```ts -import * as Schema from "effect/Schema"; - -import type { Fetch } from "@monarcode/effetch"; - -declare const api: Fetch.Client; - -const Todo = Schema.Struct({ id: Schema.Finite, title: Schema.String }); - -// GET /todos/1 -export const one = api.get("/todos/:id", { params: { id: 1 }, output: Todo }); - -// GET /todos?page=1&tags=work&tags=home -export const some = api.get("/todos", { - query: { page: 1, tags: ["work", "home"], search: undefined }, - output: Schema.Array(Todo), -}); -``` - -Every `:name` in a path is a parameter, filled in from `params`. When a path -has parameters, `params` is required, with exactly those names, and when it -has none, `params` isn't allowed. Values are URI-encoded for you. - -`query` is a plain object. Arrays repeat the key, and `null` and `undefined` -are dropped, so you can pass optional filters as they are. With Effect 4.1 or -later, a value can also be `Redacted`, such as `Redacted.make(apiKey)`: it's -sent as its value, and Effect keeps it out of its own logs and traces. - -To type an endpoint's query and send values such as dates, give the endpoint -a schema for it. See [Typed query parameters](#typed-query-parameters). - -### Sending a body - -```ts -import * as Schema from "effect/Schema"; - -import type { Fetch } from "@monarcode/effetch"; - -declare const api: Fetch.Client; - -const Todo = Schema.Struct({ - id: Schema.Finite, - title: Schema.String, - done: Schema.Boolean, - due: Schema.Date, -}); -const NewTodo = Schema.Struct({ title: Schema.String, due: Schema.Date }); - -export const create = api.post("/todos", { - input: NewTodo, - body: { title: "Write docs", due: new Date() }, - output: Todo, -}); - -export const complete = api.patch("/todos/:id", { - params: { id: 1 }, - body: { done: true }, - output: Todo, -}); - -export const upload = (file: Blob) => { - const form = new FormData(); - form.append("file", file); - return api.post("/uploads", { body: form }); -}; -``` - -A `body` is sent according to its type: - -- an `HttpBody`, a string, an `ArrayBuffer` or typed array, a `Blob` or - `File`, `FormData` and `URLSearchParams` are sent as they are; -- anything else is sent as JSON. - -Add an `input` schema, and `body` is typed by it and encoded with it before -it's sent as JSON. In `create`, `due` is a `Date` in your code and an ISO -string on the wire. To send a typed body as a form instead, such as a file -upload, see [Uploading files](#uploading-files). - -### Uploading files - -To upload files, wrap the `input` schema in `Fetch.multipart`. The body is -typed and checked by the schema, as for JSON, then sent as -`multipart/form-data`. Use `Fetch.UploadFile` for a file field: - -```ts -import * as Effect from "effect/Effect"; -import * as Schema from "effect/Schema"; - -import { Fetch } from "@monarcode/effetch"; - -const Document = Schema.Struct({ id: Schema.String }); - -export const uploadDocument = Fetch.endpoint("POST /documents", { - input: Fetch.multipart( - Schema.Struct({ - file: Fetch.UploadFile, - kind: Schema.Literals(["PASSPORT", "DRIVERS_LICENSE"]), - pages: Schema.optional(Schema.Finite), - }), - ), - output: Document, -}); - -class Api extends Fetch.Service()("Api", { - baseUrl: "https://api.example.com", -}) {} - -class DocumentApi extends Fetch.Endpoints()("DocumentApi", Api, { - upload: uploadDocument, -}) {} - -// In a browser, `file` comes from an . -export const upload = (file: File) => - Effect.gen(function* () { - const documents = yield* DocumentApi; - return yield* documents.upload({ body: { file, kind: "PASSPORT" } }); - }); -``` - -`Fetch.UploadFile` takes the files each platform can send: - -- in browsers, Node, Bun and Deno, a `Blob` or `File`; -- in React Native, the `{ uri, name, type }` object its pickers give, typed - `Fetch.NativeFile`. `uri` and `name` are required: a server only treats a - part as a file when it has a file name. `type` is optional, and a file - without one is sent as `application/octet-stream`. - -In React Native, send a `NativeFile`, not a `Blob`: React Native's `fetch` -reads a form's files from disk by `uri`, and can't send a `Blob` in a form. - -```ts -import type { Fetch } from "@monarcode/effetch"; - -// From expo-image-picker, for example -declare const asset: { - readonly uri: string; - readonly fileName?: string | null; - readonly mimeType?: string; -}; - -export const photo: Fetch.NativeFile = { - uri: asset.uri, - name: asset.fileName ?? "photo.jpg", - type: asset.mimeType, -}; -``` - -Use `Fetch.UploadFile` rather than `Schema.File`. `Schema.File` only takes a -`File`, not the `{ uri, name, type }` objects React Native's pickers give, -and `FetchTest` can't read it back from a form. - -How the schema's fields become form parts: - -- strings as they are; numbers, booleans and bigints as strings; a `Date` as - its ISO string; -- a file as a file part; -- a list as one part per item, under the same name; -- `null` and `undefined` left out. - -A form can't hold a nested object or a list of lists, so TypeScript rejects -most schemas that have one, and a value that has one makes the call die. To -send one, encode it to a string in the schema, such as -`meta: Schema.fromJsonString(Meta)`. - -
-Details: headers, errors and where it works - -- The request sets no `Content-Type`, so the platform adds the multipart - boundary. A `content-type` header from the call, the endpoint or the client - is removed, for any `FormData` body. -- The request sets no `Content-Type` before your plugins run. A plugin's - `onRequest` that sets one replaces the boundary, so leave it out for forms. -- A body that doesn't match the schema, or a value a form can't hold, makes - the call die with an `Invalid request body:` defect, as for JSON (see - [Bugs are defects](#bugs-are-defects)). So does a `{ uri, name, type }` file - outside React Native, where `FormData` would send `"[object Object]"`, or - in a field that isn't a `Fetch.UploadFile`. -- `Fetch.UploadFile` in an `input` schema without `Fetch.multipart` makes the - call die too: a file has no JSON form. -- It works wherever `input` does: on methods such as `api.post`, on endpoints, - and in `api.sse` and `api.ndjson`. -- `Fetch.multipart` returns the schema, marked. Add checks or annotations to - it as you like. A schema built around it, such as with `Schema.NullOr`, is - sent as JSON again. -- A field's encoded value must be a string, number, boolean, bigint, `Date`, - file, `null` or `undefined`, or a list of them. A schema such as - `Schema.DateTimeUtc` or `Schema.URL`, which encodes to an object, needs a - string form first, such as `Schema.DateTimeUtcFromString`. -- [`FetchTest`](#testing) reads the form back into the body a handler gets, - decoded with the schema, with files as `File`s. In Node, test with a - `Blob` or `File`, since a `{ uri, name, type }` file only works in React - Native. -- A form loses some of what the schema encodes, so `FetchTest` reads it back - as best it can: - - A `null` or `undefined` field and an empty list are left out. Such a - field comes back missing when it's optional. When it's required, it - comes back as `null` if it takes `null`, then as `[]` if it's a list, - then as `undefined`. - - Every part is a string. In a field that takes `null`, the string - `"null"` comes back as `null`, and in - `Schema.Union([Schema.String, Schema.Finite])` the string `"12"` comes - back as the number `12`. - -To check a file's size, add a check to `Fetch.UploadFile`. A -`NativeFile` has no size until it's read, so the check only looks at a -`Blob`: - -```ts -import * as Schema from "effect/Schema"; - -import { Fetch } from "@monarcode/effetch"; - -export const SmallFile = Fetch.UploadFile.check( - Schema.makeFilter( - (file) => !(file instanceof Blob) || file.size < 10_000_000, - { expected: "a file under 10 MB" }, - ), -); -``` - -- A `FormData` you build yourself still works as a `body` without `input`. - -
- -### Reading the response - -Give a call an `output` schema, and the response body is decoded with it. The -call succeeds with the decoded value, or fails with `DecodeError` if the body -doesn't match. It also sends `Accept: application/json`, unless you set an -`accept` header yourself. - -Without `output`, the call succeeds with the raw `HttpClientResponse`. That's -handy when you only care that the call worked, or want to read the body -yourself: - -```ts -import * as Schema from "effect/Schema"; - -import type { Fetch } from "@monarcode/effetch"; - -declare const api: Fetch.Client; - -// No output: succeeds with the HttpClientResponse. -export const remove = api.del("/todos/:id", { params: { id: 1 } }); - -// Nothing to decode: an empty body (204, HEAD) decodes as JSON null. -export const archive = api.post("/todos/:id/archive", { - params: { id: 1 }, - output: Schema.Void, -}); -``` - -> **Tip:** use `Schema.Finite` rather than `Schema.Number` for numbers. -> Responses are decoded with Effect's JSON codec, where `Schema.Number` also -> decodes the strings `"NaN"`, `"Infinity"` and `"-Infinity"`, and encodes -> those values back to strings. `Schema.Finite` accepts every JSON number and -> rejects the rest. - -#### Text and bytes - -`output` reads the body as JSON. For other bodies, wrap the schema: - -- `Fetch.text()` reads the body as a string, as it was sent. -- `Fetch.text(schema)` reads a single value, such as a count or a status: it - trims the text, then decodes it with a schema whose encoded side is a - string, such as `Schema.NumberFromString`. -- `Fetch.bytes()` reads the body as a `Uint8Array`, a copy of the body, for - images, PDFs and other binary bodies. - -The call sends a matching `Accept` header: `text/*, */*;q=0.1` for text, and -`*/*` for bytes, unless you set one. - -```ts -import * as Effect from "effect/Effect"; -import * as Schema from "effect/Schema"; - -import { Fetch } from "@monarcode/effetch"; - -declare const api: Fetch.Client; - -export const program = Effect.gen(function* () { - const csv = yield* api.get("/export.csv", { output: Fetch.text() }); - const count = yield* api.get("/todos/count", { - output: Fetch.text(Schema.NumberFromString), - }); - const pdf = yield* api.get("/invoices/:id", { - params: { id: 7 }, - output: Fetch.bytes(), - }); - // In a browser, Node, Bun or Deno. React Native's Blob doesn't take arrays. - return { csv, count, pdf: new Blob([pdf], { type: "application/pdf" }) }; -}); -``` - -They work wherever `output` does, endpoints included. - -- An empty body is `""` for `Fetch.text()` and a `Uint8Array` of length 0 for - `Fetch.bytes()`. For `Fetch.text(schema)`, it fails with `DecodeError`, as - for JSON. -- A body that can't be read, or doesn't match the schema, fails with - `DecodeError`. -- Error responses are still read as JSON for `error` and `statusErrors`. -- Pass the schema they return to `output` as it is. A schema built around it, - such as with `Schema.NullOr`, is read as JSON again. - -#### The body and the response - -To read the status or headers next to the decoded body, such as a total count -or an `ETag`, set `responseMode: "decoded-and-response"`. The call succeeds -with a pair: - -```ts -import * as Effect from "effect/Effect"; -import * as Schema from "effect/Schema"; - -import type { Fetch } from "@monarcode/effetch"; - -declare const api: Fetch.Client; - -const Todo = Schema.Struct({ id: Schema.Finite, title: Schema.String }); - -export const page = Effect.gen(function* () { - const [todos, response] = yield* api.get("/todos", { - query: { page: 1 }, - output: Schema.Array(Todo), - responseMode: "decoded-and-response", - }); - return { todos, total: Number(response.headers["x-total-count"]) }; -}); -``` - -- It's allowed on calls, on endpoint definitions, and on each call of an - endpoint, where the call's own mode wins. -- Without `output`, both items are the response. -- The body has already been read: use the decoded value. -- The default, `"decoded"`, gives the decoded body alone. - -### All call options - -| Option | What it does | -| -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `params` | Values for the path's `:params`. Required, with exactly those names, when the path has any; not allowed otherwise. Values are URI-encoded. | -| `query` | An object of query parameters. Arrays repeat the key, and `null` and `undefined` are dropped. | -| `headers` | Headers for this call. They win over the client's, and over the body's `content-type`. | -| `body` | Sent by its type: `HttpBody`, string, `ArrayBuffer` and typed arrays, `Blob`/`File`, `FormData` and `URLSearchParams` as they are, anything else as JSON. | -| `input` | A schema `body` is encoded with. `body` is then typed by it. Sent as JSON, or as `multipart/form-data` when wrapped in `Fetch.multipart` (see [Uploading files](#uploading-files)). | -| `output` | A schema the 2xx body is decoded with: read as JSON, or as text with `Fetch.text()` and bytes with `Fetch.bytes()`. The call then sends a matching `Accept` header (unless you set `accept`). Without it, the call succeeds with the raw `HttpClientResponse`. See [Reading the response](#reading-the-response). | -| `responseMode` | `"decoded-and-response"` makes the call succeed with `[value, response]`, to read the status and headers too. Defaults to `"decoded"`, the value alone. | -| `error` | A schema for the body of error responses, replacing the client's `defaultError`. | -| `statusErrors` | Your own errors for error responses, by status. See [Errors by status](#errors-by-status). | -| `plugins` | Plugin overrides for this call (see [Changing plugins for one call](#changing-plugins-for-one-call)). | - -### When the methods aren't enough - -- **The method is only known at runtime.** `api.request` takes it as its - first argument, before the path and the options: - - ```ts - import type * as HttpMethod from "effect/http/HttpMethod"; - - import type { Fetch } from "@monarcode/effetch"; - - declare const api: Fetch.Client; - - export const send = (method: HttpMethod.HttpMethod, path: string) => - api.request(method, path); - ``` - -- **The response is a stream of events or lines.** Use `api.sse` or - `api.ndjson` (see [Streaming responses](#streaming-responses)). - -- **You need something the methods don't do.** - `api.httpClient` is the configured `HttpClient` underneath, with the base - URL, the default headers and the plugins, but no status check and no - decoding. - -## Handling errors - -Every call's type lists the ways it can fail, so TypeScript knows which -errors you've handled and which are left. This section covers what those -errors are, how to catch them, and how to turn the API's error responses into -errors of your own. - -### What can go wrong - -A call can fail in three ways, each with its own tagged error. Plugins can add -their own, such as `timeout`'s `TimeoutError`, and -[`statusErrors`](#errors-by-status) can turn an `HttpError` into one of your -own. - -| Error | When | Fields | -| ----------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------- | -| `NetworkError` | No response: offline, DNS failure, connection refused, CORS rejection. | `method`, `url`, `cause` | -| `HttpError` | A response outside 200–299 (3xx included). | `method`, `url`, `status`, `headers`, `text`, `body` | -| `DecodeError` | A 2xx body that isn't JSON or doesn't match `output`. Only on calls with `output`. | `method`, `url`, `status`, `issue`, `message` | -| `TimeoutError` (plugin) | The `timeout` plugin's limit passed before the response arrived. | `method`, `url`, `duration` | - -### Catching errors - -Catch errors by tag with `Effect.catchTags`: - -```ts -import * as Effect from "effect/Effect"; -import * as Schema from "effect/Schema"; - -import type { Fetch } from "@monarcode/effetch"; - -declare const api: Fetch.Client; - -const Todo = Schema.Struct({ id: Schema.Finite, title: Schema.String }); -const ApiError = Schema.Struct({ code: Schema.String }); - -export const todo = (id: number) => - api.get("/todos/:id", { params: { id }, output: Todo, error: ApiError }).pipe( - Effect.catchTags({ - HttpError: (error) => - error.status === 404 - ? Effect.succeed(undefined) - : Effect.fail(error.body?.code ?? `HTTP ${error.status}`), - NetworkError: () => Effect.fail("You're offline"), - DecodeError: (error) => Effect.fail(error.message), - }), - ); -``` - -Each handler gets the error with its fields. You don't have to handle them -all: the ones you leave out stay in the type, for code further up to handle. -For a single error, `Effect.catchTag` does the same. - -`Fetch.FetchError` is the union of the three errors, and `Fetch.isFetchError` -tells them apart from other values. - -#### Catching a status - -To handle one or more statuses, use `Fetch.catchStatus`. For the common "a -404 means there's nothing there", `Fetch.optional` succeeds with -`Option.none()` on a 404 and `Option.some(value)` otherwise: - -```ts -import * as Effect from "effect/Effect"; -import * as Schema from "effect/Schema"; - -import { Fetch } from "@monarcode/effetch"; - -declare const api: Fetch.Client; - -const Todo = Schema.Struct({ id: Schema.Finite, title: Schema.String }); - -// Option: none for a 404. -export const findTodo = (id: number) => - api.get("/todos/:id", { params: { id }, output: Todo }).pipe(Fetch.optional); - -// "signed out" for a 401 or a 403. -export const me = api - .get("/me") - .pipe( - Fetch.catchStatus([401, 403], (error) => - Effect.succeed(`signed out (${error.status})`), - ), - ); -``` - -- The handler gets the `HttpError`, with `status` narrowed to the statuses you - gave, and what it returns joins the call's type. -- `HttpError` stays in the error type, since other statuses still fail with - it. -- Both work on endpoint calls too, and `catchStatus` also takes the effect - first: `Fetch.catchStatus(effect, 404, handler)`. -- A status that [`statusErrors`](#errors-by-status) maps fails with your - error, not an `HttpError`, so `catchStatus` and `optional` never see it. - Catch your error by its tag instead. -- The handler's `error.body` is `unknown`. For the typed body of an `error` - schema, use `Effect.catchTag("HttpError", …)`. - -### Typed error bodies - -APIs usually explain an error in its body, such as -`{ "code": "not_found" }`. Give Effetch a schema for it, and -`HttpError.body` is decoded and typed: - -- `defaultError`, on the client, applies to every call; -- `error`, on a call or an [endpoint](#endpoints), replaces it. - -`body` is the decoded body, or `undefined` if it didn't match the schema. -Without a schema, it's the parsed JSON. Reading it never fails the call, and -the raw body is always on `text`. - -`Fetch.HttpError.With` is the type of an `HttpError` whose `body` is `B`, -for your own function signatures. - -### Errors by status - -Often a status, or a status with a given body, means a specific error in -your app: a 404 from `GET /todos/:id` is "todo not found", a 400 with -`"code": "INVALID_ROLE"` is "invalid role", a 401 from anywhere is "session -expired". `statusErrors` maps statuses to your own error schemas, and the -call fails with your error instead of an `HttpError`. - -You can give a map in three places, and they add up: - -- on the client, for every call, such as a `401` from anywhere; -- on an [endpoint](#endpoints), for every call to it, which is where most of - them live; -- on a single call. - -```ts -import * as Effect from "effect/Effect"; -import * as Schema from "effect/Schema"; - -import { Fetch } from "@monarcode/effetch"; - -class TodoNotFound extends Schema.TaggedError()("TodoNotFound", { - message: Schema.String, -}) {} - -class InvalidRole extends Schema.TaggedError()("InvalidRole", { - code: Schema.Literal("INVALID_ROLE"), - message: Schema.String, -}) {} - -class RoleTaken extends Schema.TaggedError()("RoleTaken", { - code: Schema.Literal("ROLE_TAKEN"), - message: Schema.String, -}) {} - -class SessionExpired extends Schema.TaggedError()( - "SessionExpired", - { message: Schema.String }, -) {} - -const ApiError = Schema.Struct({ code: Schema.String }); -const Todo = Schema.Struct({ id: Schema.Finite, title: Schema.String }); -const User = Schema.Struct({ id: Schema.Finite, role: Schema.String }); - -// For every call -export class Api extends Fetch.Service()("Api", { - baseUrl: "https://api.example.com", - defaultError: ApiError, - statusErrors: { 401: SessionExpired }, -}) {} - -// For every call to an endpoint (see Endpoints) -export const getTodo = Fetch.endpoint("GET /todos/:id", { - output: Todo, - statusErrors: { 404: TodoNotFound }, -}); - -export const program = Effect.gen(function* () { - const api = yield* Api; - const todo = yield* api - .bind(getTodo)({ params: { id: 1 } }) - .pipe(Effect.catchTag("TodoNotFound", () => Effect.succeed(undefined))); - - // For one call - const user = yield* api - .post("/users/:id/roles", { - params: { id: 1 }, - input: Schema.Struct({ role: Schema.String }), - body: { role: "owner" }, - output: User, - statusErrors: { 400: [InvalidRole, RoleTaken] }, // tried in order - }) - .pipe( - Effect.catchTags({ - InvalidRole: (error) => Effect.fail(error.message), - RoleTaken: (error) => Effect.fail(error.message), - }), - ); - return { todo, user }; -}); -``` - -Before the `catchTags`, the role call fails with -`InvalidRole | RoleTaken | SessionExpired | HttpError.With<{ readonly code: string }> | NetworkError | DecodeError`. -`HttpError` stays: a response can always fail to match. - -How a non-2xx response is resolved: - -1. If the body is empty or isn't JSON, it's an `HttpError`. -2. Otherwise the schemas listed for its status are tried in order: the - call's, then the endpoint's, then the client's. The first one that - decodes the body is the error. -3. If none does, it's the `HttpError` you'd get without `statusErrors`, its - `body` decoded with `error` or `defaultError`. - -| Response | Fails with | -| ------------------------------------------------ | ---------------------------- | -| 400 `{ "code": "INVALID_ROLE", "message": "…" }` | `InvalidRole` | -| 400 `{ "code": "ROLE_TAKEN", "message": "…" }` | `RoleTaken` | -| 400 `{ "code": "MISSING_FIELD" }` | `HttpError` with `body.code` | -| 400 with an empty or non-JSON body | `HttpError` | -| 401 from any endpoint | `SessionExpired` | -| 500 | `HttpError` | - -
-Details: tags, renamed fields, unions and types - -- **The `_tag`.** Backends don't send one, so when a schema has a literal - `_tag`, as `Schema.TaggedError` classes do, Effetch adds it to the body - before decoding. A body that has its own `_tag` is decoded as it is. -- **Renamed fields.** To read `error_code` into `code`, use - `Schema.encodeKeys`: - `InvalidRole.pipe(Schema.encodeKeys({ code: "error_code" }))`. -- **Lists, not unions.** A `Schema.Union` is decoded as it is, without a - `_tag`: list its members instead. -- **2xx entries never apply**, since a 2xx is decoded with `output`. -- Plugins see the response before any of this, so `retry` still retries by - status. `onError` receives your error, and `api.httpClient` stays raw. -- Maps are copied when they're given, so changing one afterwards changes - nothing. `api.statusErrors` and a `Fetch.endpoint` definition's - `statusErrors` are those copies, frozen; an endpoint's `statusErrors` - joins its own with the client's, each status listing its schemas in the - order they're tried. -- `Fetch.StatusError` is the union of the errors in a map `M`, and - `Fetch.StatusErrorSchema` the union of its schemas, for your own - function signatures. -- A client's type includes its map: `Fetch.Client`. A client - with a map can't be passed where a plain `Fetch.Client` is expected, - since that would hide its errors. - -
- -[`examples/status-errors.ts`](examples/status-errors.ts) puts all of this in -one program, and [`examples/app`](examples/app) uses it across modules. - -### Safe to log - -Errors are made to be logged and reported: - -- `url` never includes the query string, so tokens in queries stay out of - logs. -- `HttpError.headers` are Effect `Headers`: `authorization`, `set-cookie` and - other sensitive headers print as ``. - -### Bugs are defects - -Some mistakes are bugs in the calling code, not failures to recover from at -runtime. Those make the Effect die, as a defect, rather than fail with a typed -error: - -- a missing path parameter; -- a body that can't be encoded; -- a query that doesn't match an endpoint's `query` schema; -- a body on a `GET` or `HEAD` request; -- a `baseUrl` with a query string; -- two plugins with the same name; -- a relative URL without a `baseUrl`, outside browsers. - -## Plugins - -Most APIs need the same things on every call: a token, retries when the -network drops, a time limit, a log line. Plugins add that behaviour to every -call a client makes. You list them in the client's config, and any call can -turn one off or adjust it. - -### Built-in plugins - -The built-in plugins come from `@monarcode/effetch/plugins`: - -```ts -import * as Effect from "effect/Effect"; - -import { Fetch } from "@monarcode/effetch"; -import { bearer, logger, retry, timeout } from "@monarcode/effetch/plugins"; - -declare const readToken: () => Promise; - -export class Api extends Fetch.Service()("Api", { - baseUrl: "https://api.example.com", - plugins: [ - logger({ level: "Info" }), - retry({ times: 2 }), - timeout({ duration: "10 seconds" }), - bearer({ token: () => readToken() }), - ], -}) {} - -export const withEffectToken = bearer({ token: Effect.succeed("token") }); -``` - -| Plugin | What it does | Per call | -| ------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------- | -| `bearer({ token, scheme?, refresh? })` | Sends `Authorization: Bearer `. The token is a string, a function of the request (sync or async), or an Effect, read for every request. `null`, `undefined` and `""` send no header, and an existing `Authorization` header is kept. With `refresh`, a `401` gets a new token and the request is sent again, once. See [Refreshing a token](#refreshing-a-token). | `false` | -| `logger({ level? })` | Logs one entry per call at Debug (or Info): `GET 200 (35ms)`, or `failed` with the cause, with the call's [route](#knowing-the-route) as an annotation. Never logs headers or query strings. | `false` | -| `consoleLogger(options?)` | Prints each call to the console while you develop: a line with the route, status, duration and outcome, opening a group with the full URL, headers, bodies and error. Sensitive headers, query parameters and body keys are redacted. See [Console logging](#console-logging). | `false`, its settings | -| `retry({ times?, schedule?, methods?, statuses?, retryAfter?, budget? })` | Retries network errors and 408, 429, 500, 502, 503 and 504, 2 times by default, with jittered exponential backoff from 200ms. Only idempotent methods (`GET`, `HEAD`, `OPTIONS`, `PUT`, `DELETE`) by default, so a `POST` is never sent twice. When retries run out, the last response is returned. `retryAfter` waits as `Retry-After` asks, and `budget` limits the whole call. See [Retry-After and a time limit](#retry-after-and-a-time-limit). | `false`, `{ times }`, and `{ budget }` with a budget | -| `timeout({ duration })` | Fails with `TimeoutError` and aborts the request when the response headers don't arrive in time. Downloading the body isn't covered. | `false`, `{ duration }` | - -A `bearer` token function that throws, or whose promise rejects, makes the -call die. To fail with a typed error instead, pass an Effect: its error and -services become the client's, and the client's layer (or `Fetch.make`) asks -for the services. - -Time limits apply per attempt or to the whole call: - -- **Per attempt:** `timeout`, placed after `retry` as above. Each attempt - gets the full duration, and a timed-out attempt isn't retried. -- **For the whole call:** `retry({ budget })`, every attempt and wait - included. For one call, or on a client without `retry`, wrap the call in - `Effect.timeout`. - -See [Retry-After and a time limit](#retry-after-and-a-time-limit) for both -together. - -### Refreshing a token - -To renew an expired access token without failing the call, give `bearer` a -`refresh`. When a request that `bearer` signed gets a `401`, it asks -`refresh` for a new token, then sends the request again with it: - -```ts -import { Fetch } from "@monarcode/effetch"; -import { bearer } from "@monarcode/effetch/plugins"; - -declare const tokens: { - readonly access: () => string | undefined; - readonly renew: () => Promise; -}; - -export class Api extends Fetch.Service()("Api", { - baseUrl: "https://api.example.com", - plugins: [ - bearer({ token: () => tokens.access(), refresh: () => tokens.renew() }), - ], -}) {} -``` - -The new token is used for that request only. Store it where `token` reads it, -so later requests send it too. To sign out instead, see -[Example: signing out on a 401](#example-signing-out-on-a-401). - -
-Details: how refreshing behaves - -- `refresh` is a function of the refused request, as it was sent, sync or - async, or an Effect. Like `token`, an Effect's error and services become - the client's. -- Calls refused with the same token share one refresh, so the token is - renewed once, and they all get its token or its error. Calls refused with - different tokens, such as other users' on a server, get their own. -- A call that times out or is interrupted while it waits doesn't cancel the - refresh for the others. -- The request is sent again once. If the new token is refused too, the call - ends with that `401`. -- When `refresh` gives `null`, `undefined` or `""`, such as when the session - has ended, the call ends with the `401`, and nothing more is sent. -- A request with its own `Authorization` header, sent without a token, or - with a stream body, which can't be sent twice, isn't refreshed. Neither is - a call that skips `bearer`. -- Make the refresh call itself skip `bearer`: `plugins: { bearer: false }`. - Calls made inside an Effect `refresh` never refresh, but a function that - runs the client with `Effect.runPromise` can't be told apart: a `401` to - it would wait for the refresh it's part of. -- Every method is sent again, a `POST` included: a `401` means the server - didn't act on the request. - -
- -### Retry-After and a time limit - -`retry` has two options for servers that are overloaded or slow: - -- `retryAfter`: when a retried response has a `Retry-After` header, wait as - long as it asks (`Retry-After: 120`, or an HTTP date) in place of the - schedule's delay. `true` waits up to 1 minute, and `{ max }` up to `max`. - It's off by default, so a server can't make calls wait. -- `budget`: how long the whole call may take, every attempt and wait - included. No retry is made when its wait would end at or after the budget: - the call ends with its last response or `NetworkError`. When the budget runs - out during an attempt, the attempt is aborted, and the call fails with - `TimeoutError`. Calls can override it. - -For "10 seconds per attempt, 30 seconds in all", use both `timeout` and a -budget: - -```ts -import { Fetch } from "@monarcode/effetch"; -import { retry, timeout } from "@monarcode/effetch/plugins"; - -export class Api extends Fetch.Service()("Api", { - baseUrl: "https://api.example.com", - plugins: [ - retry({ times: 5, retryAfter: true, budget: "30 seconds" }), - timeout({ duration: "10 seconds" }), - ], -}) {} - -// Per call: api.get("/report", { plugins: { retry: { budget: "2 minutes" } } }) -``` - -### Console logging - -`logger` writes one structured entry per call for production logs, and leaves -headers, query strings and bodies out. `consoleLogger` is for development: it -prints everything about a call to the console, as a group devtools can -expand. - -```ts -import { Fetch } from "@monarcode/effetch"; -import { consoleLogger } from "@monarcode/effetch/plugins"; - -declare const isDevelopment: boolean; - -export class Api extends Fetch.Service()("Api", { - baseUrl: "https://api.example.com", - plugins: [ - consoleLogger({ - enabled: isDevelopment, - slow: "1 second", - redact: { body: ["otp"] }, - }), - ], -}) {} -``` - -Each call prints a line, which opens a group with the details: - -```text -▸ GET /todos/:id 200 OK 35 ms 1.2 kB -▸ ✗ GET /todos 3.0 s → NetworkError: Failed to fetch -▸ ⚠ GET /reports/:id 200 OK 2.4 s (slow) -▾ ✗ POST /users/:id/roles 400 Bad Request 120 ms → InvalidRole: No such role - POST https://api.example.com/users/7/roles - request headers { accept: "application/json", authorization: "" } - request body { role: "owner" } - response headers { "content-type": "application/json" } - response body { code: "INVALID_ROLE", message: "No such role" } - error InvalidRole { code: "INVALID_ROLE", message: "No such role" } -``` - -It prints each call once it's over, with the error it ended with, after -[`statusErrors`](#errors-by-status) and decoding. Values are printed as -objects, so devtools can expand them. - -| Option | Default | What it does | -| --------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `enabled` | `true` | `false` prints nothing, and keeps the plugin's type, so it can stay in the list in production. | -| `detail` | `"full"` | `"summary"` prints the line alone; `"headers"` adds the URL, headers and error; `"full"` adds the bodies. | -| `only` | `"all"` | `"errors"` prints failed calls only. | -| `collapsed` | `true` | Whether groups start collapsed. `false` by default in React Native, where Metro's terminal drops collapsed groups. Node, Bun and Deno print them expanded. | -| `slow` | `false` | A duration, such as `"1 second"`: slower calls are flagged. | -| `maxBodyLength` | `10_000` | Body text longer than this is cut. JSON within it is printed as an object. | -| `redact` | | `{ headers, query, body }`: more names to redact, as strings (ignoring case, `-` and `_`) or regular expressions. `false` redacts nothing. | -| `filter` | | `(call) => boolean`: prints only the calls it accepts. `call` has the `route`, the `request`, the `response`, the `exit` and the `durationMs`. | -| `color` | `"auto"` | `"css"` (browser devtools), `"ansi"` (terminals), or `false`. `"auto"` uses `"css"` where there's a `document`, else plain text. | - -Calls can change `detail`, `only`, `collapsed`, `slow` and `maxBodyLength`, or -skip it with `false`: - -```ts -import * as Effect from "effect/Effect"; - -import { Fetch } from "@monarcode/effetch"; -import { consoleLogger } from "@monarcode/effetch/plugins"; - -class Api extends Fetch.Service()("Api", { - baseUrl: "https://api.example.com", - plugins: [consoleLogger()], -}) {} - -export const program = Effect.gen(function* () { - const api = yield* Api; - yield* api.get("/reports/export", { - plugins: { consoleLogger: { detail: "summary" } }, - }); - yield* api.get("/health", { plugins: { consoleLogger: false } }); -}); -``` - -
-Details: what it redacts - -It replaces these with ``, matching names ignoring case, `-` and -`_`: - -- headers in Effect's `Headers.CurrentRedactedNames` (`authorization`, - `cookie`, `set-cookie`, `x-api-key`), `proxy-authorization`, - `x-auth-token`, `x-access-token`, `x-refresh-token`, `x-session-token`, - `x-csrf-token`, `x-xsrf-token`, `x-client-secret` and - `x-amz-security-token`; -- keys in JSON and form bodies, at any depth: `token`, `accessToken`, - `refreshToken`, `idToken`, `authToken`, `apiToken`, `sessionToken`, - `csrfToken`, `xsrfToken`, `secret`, `clientSecret`, `apiSecret`, - `apiKey`, `privateKey`, and any name containing `password`; -- query parameters with the same names, `key`, `sig`, `signature` and the - signed-URL ones (`X-Amz-Signature`, `X-Goog-Signature`, …), values passed - as `Redacted`, and credentials in the URL (`https://user:password@…`). - -They're exact names rather than patterns, so fields such as `total_tokens` -stay visible. Plain-text bodies are printed as they are. A call's error is -printed as a copy of its fields, redacted like a body, without an -`HttpError`'s `text` or a `DecodeError`'s `issue`, which the response body -line shows. Defects are printed as they are. - -
- -
-Details: bodies, platforms and timing - -- It only reads a response body that's text: JSON, `text/*` other than event - streams, XML or a form, up to 1 MB. Effetch has read it already to check - the status or decode it, and Effect caches it. A call without `output` - returns the response itself, so its body isn't read, and stays yours to - stream. Neither is an interrupted call's. -- It writes through Effect's `Console`, so you can provide another one, with - `console.log` and groups only. React Native turns `console.error` into an - error screen. -- In React Native, groups start expanded: Metro's terminal silently drops - `console.groupCollapsed` and everything logged inside it. React Native is - detected by `navigator.product`, which it sets to `"ReactNative"`. -- It runs when the call is over, so where it sits in the plugin list doesn't - matter: a retried call is one entry, and its duration covers every - attempt. The size comes from `content-length`, or from the body when it's - read. -- When a plugin fails on a response, such as an auth plugin on a 401, that - response is shown with the plugin's error. -- `slow` that isn't a duration throws when the plugin is made. -- The request shown is the one that was sent, after plugins such as `bearer` - changed it. When no response came back, it's the one the call built, - before plugins ran. - -
- -### Plugin order - -The first plugin is the outermost: it runs first on the way out, and last on -the way back. The order in [Built-in plugins](#built-in-plugins) is the one -to use: - -- `logger` sees the whole call, retries included (`consoleLogger` sees the - whole call wherever it is); -- each retry gets its own timeout, and asks for the token again; -- a timed-out attempt isn't retried; -- `retry`'s `budget` covers every attempt and wait, while `timeout` covers - one attempt; -- a `401` that `bearer` refreshes is sent again inside the same attempt, so - it shares that attempt's timeout. - -### Changing plugins for one call - -Any call can skip a plugin with `false`, and plugins with options take part of -them. TypeScript checks the plugin names and the option types: - -```ts -import * as Effect from "effect/Effect"; - -import { Fetch } from "@monarcode/effetch"; -import { bearer, retry, timeout } from "@monarcode/effetch/plugins"; - -class Api extends Fetch.Service()("Api", { - baseUrl: "https://api.example.com", - plugins: [ - retry(), - timeout({ duration: "10 seconds" }), - bearer({ token: "token" }), - ], -}) {} - -export const program = Effect.gen(function* () { - const api = yield* Api; - - // Logging in sends no token. - yield* api.post("/auth/login", { - body: { user: "ada" }, - plugins: { bearer: false }, - }); - - // A slow export gets more time, and isn't retried. - yield* api.get("/reports/export", { - plugins: { timeout: { duration: "2 minutes" }, retry: { times: 0 } }, - }); -}); -``` - -To write your own plugins, see [Writing plugins](#writing-plugins). - -## Endpoints - -So far, most calls have spelled out their path and schemas where they're -made. That's fine for a call made once. Once a call is made from several places, you -start repeating its path, its schemas and its rules, and a mistake in one copy -still compiles. An endpoint saves them once, and gives you a function to call. - -### Why endpoints - -An HTTP call mixes two kinds of information: - -| Fixed by the API | Different on every call | -| ---------------------------------------------------- | ----------------------------------- | -| the route; the response, error and body schemas | path params, query values, the body | -| rules for that route, such as "login sends no token" | a one-off header or plugin override | - -With the methods, you write both at every call site. Three calls to -`GET /users/:id` repeat the path and the `User` schema three times, and a -mistake in one of them, such as the wrong schema or a forgotten -`bearer: false`, still compiles. An endpoint takes the first column once, when -it's defined, and only the second column when it's called. That gives you: - -- **One place per route.** A path or a schema changes in one line, and the - service that holds your endpoints lists the API you use. -- **Stricter types than a method can have.** A method only learns its HTTP - method and its `input` at the call, so it has to accept both ways. An - endpoint knows them up front: `body` is required when there's an `input` - (it's optional with `api.post`), a `GET` endpoint rejects a `body` at - compile time (`api.request("GET", …)` only dies at runtime), and the route - is checked as you type. -- **Defaults that can't be forgotten.** An endpoint's headers and plugin - overrides apply to every call. -- **A name instead of a URL.** Call sites read `users.get(…)`, and `route`, - `method` and `path` are there for query keys and log labels. - -Endpoints add no new behaviour: a call goes through the same plugins, -decoding and errors as the method it stands for, so everything in the -sections before this one applies to both. An endpoint is a saved call, not a -contract shared with a server. For that, use Effect's `HttpApi`. - -### Defining endpoints - -`Fetch.endpoint` takes a route, the method and the path in one string, and -what every call to it shares. It needs no client, so you can define endpoints -next to their schemas: - -```ts -import * as Schema from "effect/Schema"; - -import { Fetch } from "@monarcode/effetch"; - -const User = Schema.Struct({ id: Schema.Finite, name: Schema.String }); -const NewUser = Schema.Struct({ name: Schema.String }); - -export const getUser = Fetch.endpoint("GET /users/:id", { output: User }); -export const listUsers = Fetch.endpoint("GET /users", { - output: Schema.Array(User), -}); -export const createUser = Fetch.endpoint("POST /users", { - input: NewUser, - output: User, -}); - -getUser.route; // "GET /users/:id" -getUser.output; // User -``` - -The route is an uppercase method, one space, then a path that starts with `/` -or a full `http(s)://` URL. TypeScript checks it as you type: `"GTE /users"` -and `"get /users"` don't compile, and your editor suggests the methods. -`Fetch.endpoint` also throws on a malformed route, so a bad one fails as soon -as its module is imported. - -A definition is plain data: it holds the route, the schemas and the defaults, -but it can't make a call until it's bound to a client. - -### Sharing endpoints as a service - -`Fetch.Endpoints` binds a record of definitions to a client and shares them as -a service, the way `Fetch.Service` does for the client. It takes the -service's id, the client's service and the record: - -```ts -import * as Effect from "effect/Effect"; -import * as FetchHttpClient from "effect/http/FetchHttpClient"; -import * as Layer from "effect/Layer"; -import * as Schema from "effect/Schema"; - -import { Fetch } from "@monarcode/effetch"; -import { bearer } from "@monarcode/effetch/plugins"; - -declare const readToken: () => Promise; - -const User = Schema.Struct({ id: Schema.Finite, name: Schema.String }); -const NewUser = Schema.Struct({ name: Schema.String }); -const Credentials = Schema.Struct({ - user: Schema.String, - password: Schema.String, -}); -const Session = Schema.Struct({ token: Schema.String }); - -const getUser = Fetch.endpoint("GET /users/:id", { output: User }); -const listUsers = Fetch.endpoint("GET /users", { output: Schema.Array(User) }); -const createUser = Fetch.endpoint("POST /users", { - input: NewUser, - output: User, -}); -const login = Fetch.endpoint("POST /auth/login", { - input: Credentials, - output: Session, -}); - -export class Api extends Fetch.Service()("Api", { - baseUrl: "https://api.example.com", - plugins: [bearer({ token: () => readToken() })], -}) {} - -export class UserApi extends Fetch.Endpoints()("UserApi", Api, { - get: getUser, - list: listUsers, - create: createUser, - // A [definition, options] pair: logging in sends no token. - login: [login, { plugins: { bearer: false } }], -}) {} - -export const program = Effect.gen(function* () { - const users = yield* UserApi; - const ada = yield* users.create({ body: { name: "Ada" } }); - const page = yield* users.list({ query: { page: 2 } }); - const user = yield* users.get({ params: { id: ada.id } }); - return { page, user }; -}); - -export const AppLayer = UserApi.layer.pipe( - Layer.provideMerge(Api.layer), - Layer.provide(FetchHttpClient.layer), -); -``` - -Like `Fetch.Service`, the class gives you three things: - -- **`UserApi` is the service.** `yield* UserApi` gives the endpoints, each - typed with the client's plugins, `defaultError` and `statusErrors`. -- **`UserApi.layer` binds them** to the client once, when it's built. It - needs the client's service, here `Api`. The client can also be a service - you wrote by hand. -- **`UserApi.definitions` is the record you passed**, frozen. You can read - it when the module loads. - -`Layer.provideMerge` keeps `Api` in the layer's output, so code can still -`yield* Api` for one-off calls. - -Since a definition doesn't know its client: - -- **Plugin overrides are given when binding,** as in the `login` pair above, - where they're checked against the client's plugins. A definition takes no - `plugins`. -- **A definition without an `error` schema** uses the `defaultError` of the - client it's bound to. -- **Headers can be given in both.** The binding's win over the definition's. - -### Calling an endpoint - -What's fixed goes in the definition, and what changes goes in each call: - -| Defined once, on the endpoint | Passed with each call | -| --------------------------------------------------- | ------------------------- | -| `output`, `error`, `input`, `query`, `statusErrors` | `params`, `query`, `body` | -| `headers`, `responseMode`, `stream` | `headers`, `responseMode` | -| `plugins` (when binding) | `plugins` | - -- `users.get({ params: { id } })` sends exactly what - `api.get("/users/:id", { output: User, params: { id } })` does, and - returns the same Effect. -- `params` are required when the route's path has any, as with the methods. - An endpoint that needs nothing more is called with no arguments: - `users.list()`. -- With an `input` schema, `body` is required and typed by it. -- `GET`, `HEAD`, `OPTIONS` and `TRACE` endpoints take no `body` and no - `input`, and TypeScript rejects them. -- With a `query` schema, `query` is typed by it, and required when the - schema has required fields. See - [Typed query parameters](#typed-query-parameters). - -### Other ways to bind endpoints - -`Fetch.Endpoints` is built on two client methods, which you can also use -directly, such as inside your own service's layer: - -- **`api.bind(definition, options?)`** binds one definition. `options` are - the binding's `headers` and `plugins` overrides. -- **`api.bindAll(record)`** binds a record of definitions, each under its own - name. An entry can also be a `[definition, options]` pair, with the options - `api.bind` takes. Each endpoint has the type `api.bind` gives it. - -```ts -import * as Effect from "effect/Effect"; -import * as Schema from "effect/Schema"; - -import { Fetch } from "@monarcode/effetch"; -import { bearer } from "@monarcode/effetch/plugins"; - -const User = Schema.Struct({ id: Schema.Finite, name: Schema.String }); -const Session = Schema.Struct({ token: Schema.String }); - -const getUser = Fetch.endpoint("GET /users/:id", { output: User }); -const login = Fetch.endpoint("POST /auth/login", { output: Session }); - -class Api extends Fetch.Service()("Api", { - baseUrl: "https://api.example.com", - plugins: [bearer({ token: "token" })], -}) {} - -export const endpoints = Effect.gen(function* () { - const api = yield* Api; - return { - getUser: api.bind(getUser), - login: api.bind(login, { plugins: { bearer: false } }), - }; -}); - -export const sameEndpoints = Effect.gen(function* () { - const api = yield* Api; - return api.bindAll({ - getUser, - login: [login, { plugins: { bearer: false } }], - }); -}); -``` - -**`api.endpoint(route, definition)`** defines and binds in one step, where -you already have the client. Its definition can take `plugins` directly, -since it knows the client's plugins: - -```ts -import * as Effect from "effect/Effect"; -import * as Schema from "effect/Schema"; - -import { Fetch } from "@monarcode/effetch"; -import { bearer } from "@monarcode/effetch/plugins"; - -const Session = Schema.Struct({ token: Schema.String }); - -class Api extends Fetch.Service()("Api", { - baseUrl: "https://api.example.com", - plugins: [bearer({ token: "token" })], -}) {} - -export const endpoints = Effect.gen(function* () { - const api = yield* Api; - return { - login: api.endpoint("POST /auth/login", { - output: Session, - plugins: { bearer: false }, - }), - }; -}); -``` - -`api.bind(Fetch.endpoint(route, definition))` is the endpoint -`api.endpoint(route, definition)` makes, with the same type and the same -calls. Prefer `Fetch.endpoint` when: - -- endpoints should be listed next to their schemas, in a file with no client - (see [a feature-sliced app](#a-feature-sliced-app)); -- one definition serves several clients, such as staging and production; -- a tool works from your endpoints, and needs their routes and schemas - without a client, as [`FetchTest`](#testing) does. - -### Typed query parameters - -Give an endpoint a `query` schema, usually a `Schema.Struct`, and each call's -`query` is typed by it and encoded with it before it's sent. A `Schema.Class` -works too, called with an instance: - -```ts -import * as Effect from "effect/Effect"; -import * as Schema from "effect/Schema"; - -import { Fetch } from "@monarcode/effetch"; - -const Todo = Schema.Struct({ id: Schema.Finite, title: Schema.String }); - -const TodoFilters = Schema.Struct({ - done: Schema.optional(Schema.Boolean), - since: Schema.optional(Schema.Date), - pageSize: Schema.optional(Schema.Finite), -}).pipe(Schema.encodeKeys({ pageSize: "page_size" })); - -export const listTodos = Fetch.endpoint("GET /todos", { - query: TodoFilters, - output: Schema.Array(Todo), -}); - -class Api extends Fetch.Service()("Api", { - baseUrl: "https://api.example.com", -}) {} - -export const program = Effect.gen(function* () { - const api = yield* Api; - const list = api.bind(listTodos); - // GET /todos?done=false&since=2026-01-01T00%3A00%3A00.000Z&page_size=20 - return yield* list({ - query: { done: false, since: new Date("2026-01-01"), pageSize: 20 }, - }); -}); -``` - -- Each field is encoded to a string: a `Date` to its ISO string, a boolean to - `"true"` or `"false"`, a number to its digits. An array repeats the key. -- Rename keys with `Schema.encodeKeys`, as above. -- A field you leave out isn't sent, but a `null` is sent as the string - `"null"`, so prefer optional fields to nullable ones. -- A `Schema.Redacted` field is sent as its value and, with Effect 4.1 or - later, stays redacted in Effect's logs and traces. -- A query that doesn't match the schema, or a field that encodes to an - object, is a bug, not an error to handle: the call dies before anything is - sent. See [Bugs are defects](#bugs-are-defects). -- A schema with a field that has no string encoding, such as - `Schema.instanceOf(Uint8Array)`, throws when the endpoint is defined. - -The schema is the endpoint's `query` property. `client.bind`, -`client.bindAll` and `Fetch.Endpoints` keep it, and `api.endpoint` takes one -too. - -### Building an endpoint's URL - -`endpoint.url(options)` returns the URL a call with the same `params` and -`query` would go to, as a string, for a link, an `` source, or a cache -key: - -```ts -import * as Effect from "effect/Effect"; -import * as Schema from "effect/Schema"; - -import { Fetch } from "@monarcode/effetch"; - -const getFile = Fetch.endpoint("GET /files/:name", { - query: Schema.Struct({ download: Schema.optional(Schema.Boolean) }), -}); - -class Api extends Fetch.Service()("Api", { - baseUrl: "https://api.example.com", -}) {} - -// "/files/report.pdf?download=true" -export const path = getFile.url({ - params: { name: "report.pdf" }, - query: { download: true }, -}); - -export const link = Effect.gen(function* () { - const api = yield* Api; - // "https://api.example.com/files/report.pdf?download=true" - return api.bind(getFile).url({ - params: { name: "report.pdf" }, - query: { download: true }, - }); -}); -``` - -- On a bound endpoint, the URL starts with the client's `baseUrl`. -- On a definition from `Fetch.endpoint`, which has no client, it's the path - alone, unless the route is a full URL. That makes it a stable cache key - for one backend, whichever client calls it. -- The URL is built before plugins run, so anything a plugin adds, such as a - token in the query, isn't in it. -- `url` throws when a path parameter is missing or the query doesn't match - the schema, as a call would die. It encodes the query synchronously, so on - an endpoint whose query schema needs services to encode, calling it doesn't - compile. - -### Defaults and overrides - -- **Headers.** A call's headers win over the endpoint's, which win over the - client's. A bound endpoint's headers are the binding's over the - definition's. Unlike the client's, an endpoint's headers can set - `content-type`. -- **Plugins.** A call's plugin override wins over the endpoint's (given when - binding, or to `api.endpoint`), and when both give options, they're - merged. An endpoint bound with `retry: false` can still be retried in one - call with `plugins: { retry: { times: 2 } }`. -- **Schemas** belong to the endpoint, and can't be changed per call. - -Each endpoint also has `route`, `method` and `path` properties, for log labels -or cache keys. Plugins see the same route, as -[`ctx.route`](#knowing-the-route). Its `output`, `error` and `input` -properties are its schemas, for things like decoding cached data or building -test fixtures: `output` and `input` are `undefined` when the endpoint has -none, and `error` is the schema error bodies are decoded with, the -endpoint's, else the client's `defaultError`, else `Schema.Unknown`. - -### Endpoints or methods? - -Use an endpoint when a call: - -- is made from more than one place; -- has rules every call must follow, such as an auth exception or a content - type; -- sends a body with an `input` schema; -- belongs to a backend whose API you want listed in one place. - -Use a method for one-off calls, and for calls whose method or path is only -known at runtime. Mixing them is normal: keep the client next to its -endpoints, for the calls that aren't worth one. - -Avoid: - -- **`api.endpoint(…)(…)` at a call site.** That's a method call written - twice: use the method. -- **Making or binding endpoints in code that runs on every request.** Do it - once, when the layer that holds them is built, as `Fetch.Endpoints` does. -- **Passing a bound endpoint's plugin overrides at every call.** A definition - can't hold them, since it doesn't know the client's plugins: give them once, - when binding, as in `api.bind(login, { plugins: { bearer: false } })`. -- **Spreading several groups of endpoints into one object.** When two use the - same name, the later one silently wins. Nest them instead: - `{ users, todos }`, or give each group its own `Fetch.Endpoints` class. - -## Streaming responses - -Some APIs send their answer a piece at a time: progress feeds, -notifications, exports, the answers of language models. `api.sse` and -`api.ndjson` give such a body as an Effect `Stream`, one value at a time, -as it arrives. - -### Server-Sent Events - -`api.sse` reads a `text/event-stream` body. Each value is an event, with -its `event` name (`"message"` when the server sends none), its `id`, and its -`data`, decoded with `output`: - -```ts -import * as Effect from "effect/Effect"; -import * as Schema from "effect/Schema"; -import * as Stream from "effect/Stream"; - -import type { Fetch } from "@monarcode/effetch"; - -declare const api: Fetch.Client; - -const JobEvent = Schema.Struct({ percent: Schema.Finite }); - -export const followJob = (id: number) => - api.sse("/jobs/:id/events", { params: { id }, output: JobEvent }).pipe( - Stream.takeUntil((event) => event.data.percent === 100), - Stream.runForEach((event) => Effect.log(`${event.data.percent}%`)), - ); -``` - -- `output` decodes each event's `data` as JSON. Without it, or with - `Fetch.text()`, `data` is the text as it was sent. -- `method` defaults to `"GET"`. APIs that stream the answer to a request - take `"POST"` and a `body`: - - ```ts - import * as Schema from "effect/Schema"; - - import type { Fetch } from "@monarcode/effetch"; - - declare const api: Fetch.Client; - - const Prompt = Schema.Struct({ prompt: Schema.String }); - const Delta = Schema.Struct({ text: Schema.String }); - - export const complete = (prompt: string) => - api.sse("/completions", { - method: "POST", - input: Prompt, - body: { prompt }, - output: Delta, - }); - ``` - -- The request sends `Accept: text/event-stream`, unless the call or the - client sets an `accept` header. -- Events are parsed by the [WHATWG rules][sse-spec]: comment lines are - ignored, a multi-line `data` is joined with `\n`, and an `id` carries over - to the events after it. The stream doesn't reconnect, and ignores - `retry:` lines. -- A response whose `Content-Type` is set to another type than - `text/event-stream`, such as a login page from a proxy, fails the stream - with a `DecodeError`. - -`output` decodes every event, so an event whose data doesn't match it -fails the stream, after the events before it. When the server ends with a -sentinel that isn't JSON, such as `data: [DONE]`, leave `output` out, stop -at the sentinel, then decode the rest: - -```ts -import * as Schema from "effect/Schema"; -import * as Stream from "effect/Stream"; - -import type { Fetch } from "@monarcode/effetch"; - -declare const api: Fetch.Client; - -const Delta = Schema.fromJsonString(Schema.Struct({ text: Schema.String })); - -export const deltas = (prompt: string) => - api.sse("/completions", { method: "POST", body: { prompt } }).pipe( - Stream.takeWhile((event) => event.data !== "[DONE]"), - Stream.mapEffect((event) => Schema.decodeUnknownEffect(Delta)(event.data)), - ); -``` - -`api.sse` parses events with Effect's `encoding/Sse` module, which Effect -marks unstable. - -[sse-spec]: https://html.spec.whatwg.org/multipage/server-sent-events.html - -### Newline-delimited JSON - -`api.ndjson` reads an `application/x-ndjson` body (also called JSON Lines): -one JSON value per line, decoded with `output`: - -```ts -import * as Schema from "effect/Schema"; -import * as Stream from "effect/Stream"; - -import type { Fetch } from "@monarcode/effetch"; - -declare const api: Fetch.Client; - -const Row = Schema.Struct({ id: Schema.Finite, email: Schema.String }); - -export const countRows = api - .ndjson("/export/users", { output: Row }) - .pipe(Stream.runCount); -``` - -- Without `output`, each value is the parsed JSON, typed `unknown`. - `Fetch.text()` gives each line's text instead. -- Blank lines are skipped, and the last line needs no line end. -- The request sends `Accept: application/x-ndjson`, unless an `accept` - header is set. - -### Stream endpoints - -An endpoint defined with `stream: "sse"` or `stream: "ndjson"` returns a -`Stream` from its calls, however it's bound: - -```ts -import * as Effect from "effect/Effect"; -import * as Schema from "effect/Schema"; -import * as Stream from "effect/Stream"; - -import { Fetch } from "@monarcode/effetch"; - -const JobEvent = Schema.Struct({ percent: Schema.Finite }); - -const jobEvents = Fetch.endpoint("GET /jobs/:id/events", { - output: JobEvent, - stream: "sse", -}); - -class Api extends Fetch.Service()("Api", { - baseUrl: "https://api.example.com", -}) {} - -export class JobApi extends Fetch.Endpoints()("JobApi", Api, { - events: jobEvents, -}) {} - -export const lastEvent = (id: number) => - Effect.gen(function* () { - const jobs = yield* JobApi; - return yield* jobs.events({ params: { id } }).pipe(Stream.runLast); - }); -``` - -### How a stream fails - -A stream's request runs as any call does, up to the response's headers: - -- Plugins run once. `retry` and `timeout` apply to getting the response, - not to reading the body. -- When no response arrives, the stream fails with a `NetworkError`. -- An error status fails it with an `HttpError`, or a - [`statusErrors`](#errors-by-status) error, before it gives any value. -- A `204 No Content` or `205 Reset Content` gives an empty stream. - -Then the body is read as it arrives. The values before a failure are given -first. A value that doesn't match `output`, or a body that breaks off, -fails the stream with a `DecodeError`, which names the event or the line: -`Line 3 doesn't match the output schema`. - -For plugins, the call ends when the response's headers arrive. Their -`onExit` hooks, and so `logger` and `consoleLogger`, report it then, with -the time to the headers, and a `DecodeError` while reading the body doesn't -reach them. Handle it on the stream, with `Stream.catchTag("DecodeError", …)` -or `Stream.tapError`. - -### Stopping a stream - -Interrupting the stream, or taking only part of it, as with `Stream.take`, -aborts the request. Nothing else is needed to close the connection. - -A stream can't take `responseMode`, or an `output` made with -`Fetch.bytes()`. A call that passes one dies, and a definition with one -throws when it's made. - -## Pagination - -Lists are often split into pages: you ask for the first, and the response -says how to get the next. `Fetch.paginate` follows those pages for you, as a -`Stream` of pages. It calls a bound endpoint for the first page, then for the -next one, until `next` says there's none: - -```ts -import * as Effect from "effect/Effect"; -import * as Option from "effect/Option"; -import * as Schema from "effect/Schema"; -import * as Stream from "effect/Stream"; - -import { Fetch } from "@monarcode/effetch"; - -const Todo = Schema.Struct({ id: Schema.Finite, title: Schema.String }); - -const listTodos = Fetch.endpoint("GET /todos", { - query: Schema.Struct({ page: Schema.Finite }), - output: Schema.Array(Todo), -}); - -class Api extends Fetch.Service()("Api", { - baseUrl: "https://api.example.com", -}) {} - -class TodoApi extends Fetch.Endpoints()("TodoApi", Api, { - list: listTodos, -}) {} - -export const allTodos = Effect.gen(function* () { - const todos = yield* TodoApi; - return yield* Fetch.paginate(todos.list, { - start: 1, - request: (page) => ({ query: { page } }), - next: (page, number) => - page.length === 0 ? Option.none() : Option.some(number + 1), - }).pipe(Stream.flattenIterable, Stream.runCollect); -}); -``` - -- `start` is the state of the first page, such as a page number or a - cursor. -- `request(state)` gives the page's call options: `params`, `query`, `body` - and `headers`, typed by the endpoint. -- `next(page, state, response)` gives the next page's state, or - `Option.none()` after the last page. - -Each page is one value of the stream, so a page that's a list stays a list. -`Stream.flattenIterable` gives its items one by one. - -The stream is lazy: it sends a page's call only when the page is needed, so -`Stream.take(1)` sends one. A call that fails fails the stream with the -call's error. - -`Fetch.paginate` takes a bound endpoint, from `Fetch.Endpoints`, -`client.bind`, `client.bindAll` or `client.endpoint`. A definition made by -`Fetch.endpoint` needs binding first, and a stream endpoint can't be paged. - -### Cursors in headers - -When the next page's cursor is in a header, such as a `Link` header, define -the endpoint with `responseMode: "decoded-and-response"`. `next` then gets -each page's response: - -```ts -import * as Option from "effect/Option"; -import * as Schema from "effect/Schema"; - -import { Fetch } from "@monarcode/effetch"; - -declare const api: Fetch.Client; - -const Item = Schema.Struct({ id: Schema.Finite }); - -const listItems = Fetch.endpoint("GET /items", { - output: Schema.Array(Item), - responseMode: "decoded-and-response", -}); - -// The cursor is percent-encoded in the URL, and `query` encodes it again. -const nextCursor = (link: string | undefined) => - Option.fromNullishOr( - /[?&]cursor=([^&>]+)[^>]*>;\s*rel="next"/.exec(link ?? "")?.[1], - ).pipe(Option.flatMap(Option.liftThrowable(decodeURIComponent))); - -export const allItems = Fetch.paginate(api.bind(listItems), { - start: undefined as string | undefined, - request: (cursor) => (cursor === undefined ? {} : { query: { cursor } }), - next: (_items, _cursor, response) => nextCursor(response.headers.link), -}); -``` - -## Writing plugins - -When the built-in plugins don't cover what you need, write your own. The -built-in ones are written with the same API. - -### Your first plugin - -A plugin is a name and one or more hooks. This one pins the API version on -every request, with an option that a call can change: - -```ts -import * as Effect from "effect/Effect"; -import * as HttpClientRequest from "effect/http/HttpClientRequest"; - -import { Fetch } from "@monarcode/effetch"; - -export const apiVersion = Fetch.plugin({ - name: "apiVersion", - defaults: { version: "2024-06-01" }, - onRequest: (request, ctx) => - Effect.succeed( - HttpClientRequest.setHeader(request, "api-version", ctx.options.version), - ), -}); - -class Api extends Fetch.Service()("Api", { - baseUrl: "https://api.example.com", - plugins: [apiVersion], -}) {} - -export const program = Effect.gen(function* () { - const api = yield* Api; - yield* api.get("/reports", { - plugins: { apiVersion: { version: "2025-01-01" } }, - }); -}); -``` - -`Fetch.plugin` infers the plugin's name, options, errors and services from -what you give it, so calls can override `apiVersion` by name, and their -options are checked. `ctx.options` is the plugin's `defaults` merged with the -call's override, so a plugin needs `defaults` to take options. - -### Hooks - -| Hook | Runs | -| ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- | -| `onRequest(request, ctx)` | Before the request is sent, in array order. Returns the request to send, or fails. It sees the full URL and the client's headers. | -| `onResponse(response, ctx)` | On every response, non-2xx included, in reverse order. Returns the response, or fails. The status check and decoding come after all plugins. | -| `onError(error, ctx)` | After a call fails or dies, in array order. It can't change the outcome. | -| `onExit(exit, ctx)` | After every call, whatever the outcome, in array order, after `onError`. It can't change the outcome. | -| `wrap(client, options, route)` | Wraps the plugins after it and the network, for retries, timeouts and the like. It can add errors but can't remove them. | - -`ctx.request` is the request: in `onResponse`, the one this plugin passed on; -in `onError` and `onExit`, the one the call built. - -`onExit` gets the call's `Exit`: its result (the decoded `output`, or the -response for a call without one), or the cause of its failure, defect or -interruption. Its `ctx` also has: - -- `response`: the one the plugins returned; when a plugin failed after a - response arrived, the last one the network sent; `undefined` when none - arrived; -- `durationMs`: the time from sending the request to decoding the body, - retries included. - -It suits logging and metrics, and is what `consoleLogger` uses: - -```ts -import * as Effect from "effect/Effect"; -import * as Exit from "effect/Exit"; - -import { Fetch } from "@monarcode/effetch"; - -declare const record: (route: string, ok: boolean, durationMs: number) => void; - -export const metrics = Fetch.plugin({ - name: "metrics", - onExit: (exit, ctx) => - Effect.sync(() => record(ctx.route, Exit.isSuccess(exit), ctx.durationMs)), -}); -``` - -The call returns once every `onExit` hook is done, so keep them quick, and -fork anything slow. - -### Knowing the route - -`ctx.route` is the call's method and path as written, before the params are -filled in: `"GET /users/:id"`, whether the call was -`api.get("/users/:id", …)` or an [endpoint](#endpoints). It's the same for -every user ID, so it's what to group logs, metrics and error reports by. It's -`undefined` for requests sent through `client.httpClient`. - -A `wrap` reads it from its third argument, an Effect like `options`: - -```ts -import * as Effect from "effect/Effect"; -import * as HttpClient from "effect/http/HttpClient"; - -import { Fetch } from "@monarcode/effetch"; - -declare const report: (error: unknown, route: string | undefined) => void; - -export const errorReporter = Fetch.plugin({ - name: "errorReporter", - onError: (error, ctx) => Effect.sync(() => report(error, ctx.route)), -}); - -export const timing = Fetch.plugin({ - name: "timing", - wrap: (client, _options, route) => - HttpClient.transform(client, (response, request) => - Effect.gen(function* () { - const label = (yield* route) ?? request.url; - return yield* Effect.withLogSpan(response, label); - }), - ), -}); -``` - -### Example: signing out on a 401 - -The classic plugin: send the session's token, and when the API answers `401`, -sign out and fail with a typed `SessionExpired`. To renew the token instead, -see [Refreshing a token](#refreshing-a-token). - -```ts -import * as Context from "effect/Context"; -import * as Data from "effect/Data"; -import * as Effect from "effect/Effect"; -import * as HttpClientRequest from "effect/http/HttpClientRequest"; - -import { Fetch } from "@monarcode/effetch"; - -export class SessionExpired extends Data.TaggedError("SessionExpired")<{}> {} - -export class Session extends Context.Service< - Session, - { - readonly accessToken: Effect.Effect; - readonly signOut: Effect.Effect; - } ->()("Session") {} - -export const auth = Fetch.plugin({ - name: "auth", - onRequest: (request) => - Effect.gen(function* () { - const session = yield* Session; - const token = yield* session.accessToken; - return token === undefined - ? request - : HttpClientRequest.bearerToken(request, token); - }), - onResponse: (response) => - Effect.gen(function* () { - if (response.status !== 401) { - return response; - } - const session = yield* Session; - yield* session.signOut; - return yield* new SessionExpired(); - }), -}); - -// Api.layer now needs Session; calls fail with SessionExpired too. -export class Api extends Fetch.Service()("Api", { - baseUrl: "https://api.example.com", - plugins: [auth], -}) {} -``` - -### Example: a deadline with its own error - -A `wrap` that adds its own error, with an option calls can override: - -```ts -import * as Data from "effect/Data"; -import * as Effect from "effect/Effect"; -import * as HttpClient from "effect/http/HttpClient"; - -import { Fetch } from "@monarcode/effetch"; - -export class TooSlow extends Data.TaggedError("TooSlow")<{ - readonly url: string; -}> {} - -export const deadline = Fetch.plugin({ - name: "deadline", - defaults: { millis: 5000 }, - wrap: (client, options) => - HttpClient.transform(client, (response, request) => - Effect.gen(function* () { - const { millis } = yield* options; - return yield* Effect.timeoutOrElse(response, { - duration: millis, - orElse: () => Effect.fail(new TooSlow({ url: request.url })), - }); - }), - ), -}); -``` - -### Tips - -- Services a plugin needs are required once, by the client's layer (or by - `Fetch.make`). Calls don't need them. Services provided around a call win - over those the client was built with. -- Plugin names must be unique. -- Write `wrap` bodies with `Effect.gen`. A ternary that returns two different - Effects can't be typed. -- Pass plugin lists inline, or let TypeScript infer them. Annotating a list as - `Fetch.Plugin.Any[]` erases the plugins' types. - -## Structuring an app - -A client is declared once, and endpoints are bound to it once, in a layer. -Where each piece lives depends on the size of your app. These are patterns, -not rules: Effetch works the same way whichever you pick. - -### A small app - -Keep the client in one file, and each area's endpoints in its own file, as a -`Fetch.Endpoints` class. One layer puts them together: - -```ts -import * as Effect from "effect/Effect"; -import * as FetchHttpClient from "effect/http/FetchHttpClient"; -import * as Layer from "effect/Layer"; -import * as Schema from "effect/Schema"; - -import { Fetch } from "@monarcode/effetch"; -import { bearer } from "@monarcode/effetch/plugins"; - -const User = Schema.Struct({ id: Schema.Finite, name: Schema.String }); -const NewUser = Schema.Struct({ name: Schema.String }); -const Todo = Schema.Struct({ id: Schema.Finite, title: Schema.String }); - -// api.ts -export class Api extends Fetch.Service()("Api", { - baseUrl: "https://api.example.com", - plugins: [bearer({ token: "token" })], -}) {} - -// users.ts -export class Users extends Fetch.Endpoints()("Users", Api, { - get: Fetch.endpoint("GET /users/:id", { output: User }), - create: Fetch.endpoint("POST /users", { input: NewUser, output: User }), - login: [ - Fetch.endpoint("POST /auth/login", { output: User }), - { plugins: { bearer: false } }, - ], -}) {} - -// todos.ts -export class Todos extends Fetch.Endpoints()("Todos", Api, { - list: Fetch.endpoint("GET /todos", { output: Schema.Array(Todo) }), -}) {} - -// layer.ts -export const AppLayer = Layer.mergeAll(Users.layer, Todos.layer).pipe( - Layer.provideMerge(Api.layer), - Layer.provide(FetchHttpClient.layer), -); - -// anywhere -export const program = Effect.gen(function* () { - const users = yield* Users; - const api = yield* Api; // for one-off calls - const user = yield* users.get({ params: { id: 1 } }); - yield* api.post("/users/:id/ping", { params: { id: user.id } }); - return user; -}); -``` - -The plugin override on `login` is checked against `Api`'s plugins, and every -endpoint's errors are typed with `Api`'s `defaultError` and `statusErrors`. - -To make endpoints with `client.endpoint` instead, write each area as a -function of the client, typed `Effect.Success`, so overrides and -errors are still checked against your plugins and `defaultError`: - -```ts -import * as Effect from "effect/Effect"; -import * as Schema from "effect/Schema"; - -import { Fetch } from "@monarcode/effetch"; -import { bearer } from "@monarcode/effetch/plugins"; - -const User = Schema.Struct({ id: Schema.Finite, name: Schema.String }); - -class Api extends Fetch.Service()("Api", { - baseUrl: "https://api.example.com", - plugins: [bearer({ token: "token" })], -}) {} - -export const users = (api: Effect.Success) => ({ - get: api.endpoint("GET /users/:id", { output: User }), - login: api.endpoint("POST /auth/login", { - output: User, - plugins: { bearer: false }, - }), -}); -``` - -### A feature-sliced app - -When your app is split into feature modules, each with its own schemas, the -client becomes shared infrastructure that knows nothing about the modules. -Each module defines its endpoints next to its schemas, with no client, and -binds them to the client in its data layer: - -```text -src/ -├── infrastructure/http/ -│ └── app-api-client.ts the client: base URL, error body, plugins -├── modules/ -│ ├── todos/ -│ │ ├── contract/ schemas, and endpoints defined with Fetch.endpoint -│ │ ├── data/ the endpoints, bound to AppApiClient -│ │ ├── application/ workflows that take more than one call -│ │ └── public.ts -│ └── wallet/ -└── runtime.ts modules, on top of clients, on top of HttpClient -``` - -> **This layout is a personal preference,** the one Effetch's author uses in -> their own apps, and Effetch doesn't depend on it. Rename, merge or split the -> folders to suit your project. What carries over is that modules import the -> client, never the other way around, and that endpoints are bound once, in a -> layer. - -```ts -import * as Config from "effect/Config"; -import * as Effect from "effect/Effect"; -import * as FetchHttpClient from "effect/http/FetchHttpClient"; -import * as Layer from "effect/Layer"; -import * as Schema from "effect/Schema"; - -import { Fetch } from "@monarcode/effetch"; - -// infrastructure/http/app-api-client.ts: how to reach the backend, nothing else -export class AppApiClient extends Fetch.Service()( - "AppApiClient", - { baseUrl: Config.String("APP_API_URL") }, -) {} - -// modules/todos/contract/todos.ts: schemas and endpoints, no client -const Todo = Schema.Struct({ id: Schema.Finite, title: Schema.String }); -const NewTodo = Schema.Struct({ title: Schema.String }); - -export const listTodos = Fetch.endpoint("GET /todos", { - output: Schema.Array(Todo), -}); -export const getTodo = Fetch.endpoint("GET /todos/:id", { output: Todo }); -export const createTodo = Fetch.endpoint("POST /todos", { - input: NewTodo, - output: Todo, -}); - -// modules/todos/data/todo.api.ts: the endpoints, bound, as the module's service -export class TodoApi extends Fetch.Endpoints()( - "TodoApi", - AppApiClient, - { - list: listTodos, - get: getTodo, - create: createTodo, - }, -) {} - -// runtime.ts -export const AppLayer = TodoApi.layer.pipe( - Layer.provideMerge(AppApiClient.layer), - Layer.provide(FetchHttpClient.layer), -); - -// anywhere -export const program = Effect.gen(function* () { - const todos = yield* TodoApi; - const todo = yield* todos.create({ body: { title: "Write docs" } }); - return yield* todos.get({ params: { id: todo.id } }); -}); -``` - -This scales well as the app grows: - -- **The client file stays the same size,** however many endpoints the app - has, and it never imports a module: dependencies point from the modules to - the infrastructure. -- **A module with 20 endpoints has 20 definitions** in its own `contract/` - folder, beside their schemas, and 20 one-line entries in its - `Fetch.Endpoints` class in `data/`. When they serve separate concerns, - split them into several services, each in its own file. -- **Every module's data service is its endpoints,** as `TodoApi` is here: one - line per operation, and every type inferred, so every module's `data/` - folder looks the same. -- **An operation that isn't one HTTP call** (it combines calls, reshapes a - response or adds a domain error) is a workflow over those endpoints, in the - module's `application/` folder. -- **Declare a service's interface by hand only when you need another - implementation,** such as an offline one or a fake for UI work, and - implement it with the endpoints. - -`client.endpoint` fits this layout too: make the endpoints in `data/`, and -import only the schemas from `contract/`. Define them with `Fetch.endpoint` -when something should read the routes and schemas without a client. -[`examples/app`](examples/app) is a complete app in this layout, with two -modules and two backends: `todos` declares its definitions with -`Fetch.Endpoints`, and `wallet` uses `client.endpoint`. - -### Several backends - -Declare one client per backend, each with its own id, `baseUrl`, -`defaultError` and plugins. Each module uses the client of the backend it -talks to, and one `HttpClient` layer serves them all. - -- Plugins are values: one `bearer` can serve several clients. -- `ctx.route` has no host. A plugin that groups by route and is shared by - several clients should take the backend's name, so each client gets its own - instance. -- Catch a backend's `HttpError` next to its calls, where `body` has that - backend's error shape. - -[`examples/backends.ts`](examples/backends.ts) does this in one file, and -[`examples/app`](examples/app) across modules. - -## Testing - -Effetch never touches the network itself: it sends every request through the -`HttpClient` you provide. In tests, `@monarcode/effetch/test` gives you a fake -one, made from your endpoints, so your code runs as it does in production: -the real client, with its plugins, `defaultError` and `statusErrors`. - -### A fake backend from your endpoints - -`FetchTest.layer` takes a list of handlers, one per route, and is an -`HttpClient` layer. Provide it where `FetchHttpClient.layer` goes. A client -whose `layer` is [overridden](#providing-the-client) to provide its own -`HttpClient` ignores it, so test with a layer that doesn't: - -```ts -import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; -import * as Schema from "effect/Schema"; - -import { Fetch } from "@monarcode/effetch"; -import { FetchTest } from "@monarcode/effetch/test"; - -const Todo = Schema.Struct({ - id: Schema.Finite, - title: Schema.String, - due: Schema.Date, -}); -const NewTodo = Schema.Struct({ title: Schema.String, due: Schema.Date }); - -class TodoNotFound extends Schema.TaggedError()("TodoNotFound", { - message: Schema.String, -}) {} - -const getTodo = Fetch.endpoint("GET /todos/:id", { - output: Todo, - statusErrors: { 404: TodoNotFound }, -}); -const createTodo = Fetch.endpoint("POST /todos", { - input: NewTodo, - output: Todo, -}); -const listTodos = Fetch.endpoint("GET /todos", { output: Schema.Array(Todo) }); - -class Api extends Fetch.Service()("Api", { - baseUrl: "https://api.test", -}) {} - -class TodoApi extends Fetch.Endpoints()("TodoApi", Api, { - get: getTodo, - create: createTodo, - list: listTodos, -}) {} - -const Backend = FetchTest.layer([ - FetchTest.respond(getTodo, ({ params }) => - // params are strings, as they are in the URL - Effect.succeed({ - id: Number(params.id), - title: "Write docs", - due: new Date(0), - }), - ), - FetchTest.respond(createTodo, ({ body }) => - Effect.succeed({ id: 2, ...body }), - ), - FetchTest.fail(listTodos, 503), -]); - -const TestLayer = TodoApi.layer.pipe( - Layer.provide(Api.layer), - Layer.provide(Backend), -); - -export const test = Effect.gen(function* () { - const todos = yield* TodoApi; - const todo = yield* todos.get({ params: { id: 1 } }); - // todo.due is a Date again: it went over the wire as a string - return todo; -}).pipe(Effect.provide(TestLayer)); -``` - -What a handler gets and returns is typed by its endpoint, and checked as a -real backend would check it: - -- **`params`** has the route's params, as strings. -- **`body`** is decoded with the endpoint's `input` schema, so `body.due` is a - `Date` here. A [multipart](#uploading-files) body is read back from the - form, with its files as `File`s. -- **`query`** is decoded with the endpoint's - [query schema](#typed-query-parameters), if it has one, and is the raw - query, as strings, otherwise. -- **The result** has `output`'s type, and is encoded with `output` before - it's sent, so a `Date` goes over the wire as a string, as in production. - With [`Fetch.text()` or `Fetch.bytes()`](#text-and-bytes), it's sent as - text or bytes. - -A body, query or result that doesn't match its schema is a defect that names -the route: it's a bug in the code under test, or in the test. Handlers work -the same for definitions made with `Fetch.endpoint`, endpoints made with -`client.endpoint` or `client.bind`, and a `Fetch.Endpoints` class's -`definitions`. - -`FetchTest` doesn't depend on a test runner: a test is an Effect, so run it -with `it.effect` from `@effect/vitest`, or with `Effect.runPromise` in Jest, -Bun or Deno. - -### Errors and other statuses - -To answer every request to an endpoint with an error, use `FetchTest.fail`, -with a status and an optional body. The body is encoded with the endpoint's -`statusErrors` schema for that status, then its `error` schema, so the client -decodes it back into your domain error: - -```ts -import * as Schema from "effect/Schema"; - -import { Fetch } from "@monarcode/effetch"; -import { FetchTest } from "@monarcode/effetch/test"; - -class TodoNotFound extends Schema.TaggedError()("TodoNotFound", { - message: Schema.String, -}) {} - -const getTodo = Fetch.endpoint("GET /todos/:id", { - statusErrors: { 404: TodoNotFound }, -}); - -export const Backend = FetchTest.layer([ - // The call fails with a TodoNotFound. - FetchTest.fail(getTodo, 404, new TodoNotFound({ message: "No todo 9" })), -]); -``` - -A handler answers with another status by returning `FetchTest.reply(status, -body)`, such as a `404` for one id and the todo for the others. A reply's body -is sent as it is, as a call's `body` without `input` is: no body, a string -as text, bytes as bytes, a `Blob`, `FormData` or `URLSearchParams` as it is, -and anything else as JSON. For a `2xx` with a typed body, such as a `201`, pass -`{ status: 201 }` as `respond`'s third argument instead: - -```ts -import * as Effect from "effect/Effect"; -import * as Schema from "effect/Schema"; - -import { Fetch } from "@monarcode/effetch"; -import { FetchTest } from "@monarcode/effetch/test"; - -const Todo = Schema.Struct({ id: Schema.Finite, title: Schema.String }); -const getTodo = Fetch.endpoint("GET /todos/:id", { output: Todo }); -const createTodo = Fetch.endpoint("POST /todos", { - input: Schema.Struct({ title: Schema.String }), - output: Todo, -}); - -export const Backend = FetchTest.layer([ - FetchTest.respond(getTodo, ({ params }) => - Effect.succeed( - params.id === "1" - ? { id: 1, title: "Write docs" } - : FetchTest.reply(404, { message: `No todo ${params.id}` }), - ), - ), - FetchTest.respond( - createTodo, - ({ body }) => Effect.succeed({ id: 2, ...body }), - { - status: 201, - headers: { location: "/todos/2" }, - }, - ), -]); -``` - -### Stream endpoints in tests - -A handler for a [stream endpoint](#stream-endpoints) returns a list, and -`FetchTest` sends it as the stream's body: events for `stream: "sse"`, each -with its `data` and an optional `event` and `id`, and values for -`stream: "ndjson"`. Each value is encoded with the endpoint's `output`: - -```ts -import * as Effect from "effect/Effect"; -import * as Schema from "effect/Schema"; - -import { Fetch } from "@monarcode/effetch"; -import { FetchTest } from "@monarcode/effetch/test"; - -const JobEvent = Schema.Struct({ percent: Schema.Finite }); - -const jobEvents = Fetch.endpoint("GET /jobs/:id/events", { - output: JobEvent, - stream: "sse", -}); - -export const Backend = FetchTest.layer([ - FetchTest.respond(jobEvents, ({ params }) => - Effect.succeed([ - { data: { percent: 50 } }, - { event: "done", id: params.id, data: { percent: 100 } }, - ]), - ), -]); -``` - -The whole body is sent at once. To test how your code handles values that -arrive slowly, or a body that breaks off, use -[a hand-written `HttpClient`](#a-hand-written-httpclient) whose `Response` -has a `ReadableStream` body. - -### Checking what was sent - -The layer also provides `FetchTest.Recorder`, which keeps every request it -received, with a new record each time the layer is built. -`FetchTest.requests` reads it. Under a client's layer, `Layer.provide` would -hide it, so use `Layer.provideMerge`: - -```ts -import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; - -import { Fetch } from "@monarcode/effetch"; -import { FetchTest } from "@monarcode/effetch/test"; - -class Api extends Fetch.Service()("Api", { - baseUrl: "https://api.test", -}) {} - -const deleteTodo = Fetch.endpoint("DELETE /todos/:id"); - -const Backend = FetchTest.layer([ - FetchTest.respond(deleteTodo, () => Effect.void), -]); - -export const test = Effect.gen(function* () { - const api = yield* Api; - yield* api.bind(deleteTodo)({ params: { id: 1 } }); - const [sent] = yield* FetchTest.requests; - // sent.method: "DELETE", sent.url: "https://api.test/todos/1", - // sent.route: "DELETE /todos/:id", sent.params: { id: "1" } - return sent; -}).pipe(Effect.provide(Api.layer.pipe(Layer.provideMerge(Backend)))); -``` - -Each recorded request has its `method`, `url`, the `route` and `params` it -matched, its raw `query`, its `headers`, and its `body`, read back as JSON, -text or bytes. - -### How requests are matched - -- **Method and path.** A route matches a request with the same method, whose - path ends with the route's path. So `GET /todos/:id` answers - `https://api.test/v1/todos/1`, whatever the client's `baseUrl`. To match - the whole URL instead, pass the `baseUrl` to the layer: - `FetchTest.layer(handlers, { baseUrl: "https://api.test/v1" })`. -- **The root route,** `GET /`, matches the path `/` alone, since every path - with a trailing slash ends with it. Under a `baseUrl` with a path, pass - that `baseUrl` to the layer. -- **The best match wins.** When several routes match, the one with the most - segments wins, then the one with the most literal segments, so - `GET /todos/count` wins over `GET /todos/:id`. After that, the one listed - first wins. -- **Absolute routes** such as `POST https://uploads.example.com/files` match - that URL only. -- **No match is a defect,** whose message lists the backend's routes, and the - ones that match the path with another method: - - ```text - FetchTest: no handler for POST https://api.test/todos/1. - GET /todos/:id matches its path, but not its method. - The handlers are: - - GET /todos/:id - ``` - -A handler can use services, such as a clock or a store of fake data. The -layer then needs them, and runs its handlers with the services it was built -with, and those of the call they answer, which win when both have one. - -### A hand-written HttpClient - -For what a fake backend doesn't do, such as a network failure or a slow -response, provide an `HttpClient` of your own: - -```ts -import * as Effect from "effect/Effect"; -import * as HttpClient from "effect/http/HttpClient"; -import * as HttpClientResponse from "effect/http/HttpClientResponse"; -import * as Layer from "effect/Layer"; -import * as Schema from "effect/Schema"; - -import { Fetch } from "@monarcode/effetch"; - -const Todo = Schema.Struct({ id: Schema.Finite, title: Schema.String }); - -class Api extends Fetch.Service()("Api", { - baseUrl: "https://api.test", -}) {} - -const sent: Array = []; - -const TestHttpClient = Layer.succeed( - HttpClient.HttpClient, - HttpClient.make((request, url) => { - sent.push(`${request.method} ${url.href}`); - return Effect.succeed( - HttpClientResponse.fromWeb( - request, - Response.json({ id: 1, title: "Write docs" }), - ), - ); - }), -); - -const program = Effect.gen(function* () { - const api = yield* Api; - return yield* api.get("/todos/:id", { params: { id: 1 }, output: Todo }); -}); - -const todo = await Effect.runPromise( - program.pipe(Effect.provide(Api.layer.pipe(Layer.provide(TestHttpClient)))), -); -// todo: { id: 1, title: "Write docs" }; sent: ["GET https://api.test/todos/1"] -``` - -## Platform notes - -Effetch has no platform-specific imports or builds, and runs wherever Effect's -`HttpClient` does: browsers, React Native, Node 20 or newer, Bun and Deno. -Two platforms need a little setup. - -### Browsers - -Effect's `HttpClient` adds `traceparent` and `b3` tracing headers to every -request. Cross-origin calls to APIs that don't allow those headers then fail -the CORS preflight. Turn propagation off in the layer that makes the client, -and it applies to all its calls: - -```ts -import * as FetchHttpClient from "effect/http/FetchHttpClient"; -import * as HttpClient from "effect/http/HttpClient"; -import * as Layer from "effect/Layer"; - -import { Fetch } from "@monarcode/effetch"; - -export class Api extends Fetch.Service()("Api", { - baseUrl: "https://api.example.com", -}) {} - -export const ApiLive = Api.layer.pipe( - Layer.provide(Layer.succeed(HttpClient.TracerPropagationEnabled)(false)), - Layer.provide(FetchHttpClient.layer), -); -``` - -In a browser, a relative path without a `baseUrl` is resolved against the -page's URL. - -### React Native - -- Effetch doesn't use `URL` itself. Effect's `HttpClient` does, including - `searchParams`. Expo provides a standard `URL`. In a React Native app - without Expo, install a polyfill such as `react-native-url-polyfill`. -- Effetch and Effect use package `exports` (`effect/http/HttpClient`, - `@monarcode/effetch/plugins`). Metro resolves them by default from React - Native 0.79 (Expo SDK 53). On older versions, set - `resolver.unstable_enablePackageExports = true` in `metro.config.js`. -- `FetchHttpClient.layer` uses the global `fetch`. -- React Native's `fetch` doesn't stream response bodies, so `api.sse`, - `api.ndjson` and stream endpoints fail with a `DecodeError` there. In - Expo, provide the `fetch` from `expo/fetch`, which streams, as - `FetchHttpClient.Fetch`: - `Layer.succeed(FetchHttpClient.Fetch)(expoFetch as typeof globalThis.fetch)`. -- To upload a file a picker gave you, send its `{ uri, name, type }` in a - `Fetch.UploadFile` field (see [Uploading files](#uploading-files)). React - Native's `FormData` reads the file from disk by `uri`, and can't send a - `Blob`. -- Metro's terminal drops `console.groupCollapsed` and everything inside it, - so `consoleLogger` doesn't collapse its groups in React Native (see the - details under [Console logging](#console-logging)). - -## Coming from axios or ky - -The following table maps what you know from axios and ky to Effetch: - -| axios or ky | Effetch | -| ------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | -| `axios.create`, `ky.create` | [`Fetch.Service`](#declaring-a-client), or [`Fetch.make`](#fetchservice-or-fetchmake) in a script | -| `ky.extend`, a client per API version | A second `Fetch.Service` from `{ ...Api.config, baseUrl }` (see [A client from another](#a-client-from-another)) | -| `baseURL`, `prefixUrl` | `baseUrl`, a string or an Effect such as a `Config` | -| `params`, `searchParams` | `query`, a plain object, or typed by an endpoint's [`query` schema](#typed-query-parameters) | -| Interceptors, `hooks.beforeRequest` and `hooks.afterResponse` | A [plugin](#writing-plugins)'s `onRequest` and `onResponse` | -| `hooks.beforeError` | `Effect.mapError` on the call. A plugin's `onError` sees errors but can't change them | -| `retry`, `timeout` | The [`retry` and `timeout` plugins](#built-in-plugins), which a call can turn off or adjust | -| ky's `totalTimeout` | `retry({ budget })`, or `Effect.timeout` around a call | -| `AbortController`, `signal` | Interruption: `Fiber.interrupt`, `Effect.race`, `Effect.timeout`. An interrupted call aborts its request | -| `validateStatus`, `throwHttpErrors: false` | `Effect.catchTag("HttpError", …)`, [`statusErrors`](#errors-by-status), or [`Fetch.catchStatus`](#catching-a-status) and `Fetch.optional` | -| `error.response.data`, ky's `HTTPError` body | `HttpError.body`, decoded with `defaultError` or the call's `error` schema | -| `ky.get(url).json()`, `axios.get(url)` | `api.get(path, { output: Schema })`: the body is checked, not cast | -| `responseType: "text"` or `"arraybuffer"` | `output: Fetch.text()` or `Fetch.bytes()` (see [Text and bytes](#text-and-bytes)) | -| Reading the status and headers with the data | `responseMode: "decoded-and-response"` (see [The body and the response](#the-body-and-the-response)) | -| `responseType: "stream"`, `onDownloadProgress` for events | [`api.sse` and `api.ndjson`](#streaming-responses) | -| A `FormData` body built by hand | `input: Fetch.multipart(schema)`, a typed body sent as a form (see [Uploading files](#uploading-files)) | -| The `fetch` option or an `adapter` in tests | [`FetchTest`](#testing), or any `HttpClient` layer | - -## Reference - -### Limitations - -- A path parameter is a whole segment: `/files/:name.json` has one parameter - called `name.json`. -- Path parameters can't be optional. Define one endpoint per path, or pass - the value in `query`. -- Paths shouldn't contain `?` or `#`. Pass query parameters with `query`. -- `timeout`, and the duration `logger` logs, cover the time until the - response headers arrive, not downloading the body. `consoleLogger`'s - duration, and an `onExit` hook's `durationMs`, include decoding the body. -- Two plugins with the same name are only caught when the client is made. -- Streams don't reconnect: `api.sse` ignores `retry:` lines and the - `Last-Event-ID` header. Repeat the call, with the last `id` in a header, - to pick up where a stream stopped. -- For a stream, plugins see the call end when the response's headers - arrive: they don't see the body being read, or a `DecodeError` while - reading it, and `timeout` doesn't bound it. - -### API - -Every export is documented, with an example, in the type declarations your -editor shows. This list says where each one is covered here. - -`@monarcode/effetch`, as the `Fetch` namespace: - -- `Service`, `ServiceClass` (and `ServiceClass.Any`), `isService`: - [declaring a client](#declaring-a-client). -- `make`, `ClientConfig`, `Client`: [setting up a client](#setting-up-a-client) - and [making calls](#making-calls). -- `endpoint`, `UnboundEndpoint`, `UnboundDefinition`, `AnyUnboundEndpoint`: - [defining endpoints](#defining-endpoints). -- `Endpoints`, `EndpointsClass`: - [sharing endpoints as a service](#sharing-endpoints-as-a-service). -- `BindMethod`, `BindOptions`, `BindAllMethod`, `EndpointDefinitions`, - `EndpointEntry`, `BoundEndpoint`, `BoundEndpoints`: - [other ways to bind endpoints](#other-ways-to-bind-endpoints). -- `Endpoint`, `EndpointMethod`, `EndpointDefinition`, `EndpointOptions`, - `EndpointBody`, `EndpointArgs`, `EndpointRoute`, `ValidRoute`, - `RouteMethod`, `RoutePath`: [endpoints](#endpoints). -- `QuerySchema`, `EndpointQuery`: - [typed query parameters](#typed-query-parameters). -- `EndpointUrlOptions`, `EndpointUrlArgs`: - [building an endpoint's URL](#building-an-endpoints-url). -- `multipart`, `UploadFile`, `UploadFileSchema`, `NativeFile`, - `MultipartSchema`, `MultipartFields`, `MultipartValue`: - [uploading files](#uploading-files). -- `text`, `bytes`, `TextSchema`, `BytesSchema`: - [text and bytes](#text-and-bytes). -- `NetworkError`, `HttpError` (and `HttpError.With`), `DecodeError`, - `FetchError`, `isFetchError`: [errors](#handling-errors). -- `StatusError`, `StatusErrorMap`, `StatusErrorSchema`, - `StatusErrorServices`: [errors by status](#errors-by-status). -- `catchStatus`, `optional`, `CaughtStatus`: - [catching a status](#catching-a-status). -- `SseEvent`, `StreamElement`, `StreamFormat`, `StreamMethod`, - `StreamOptions`: [streaming responses](#streaming-responses). -- `paginate`, `PaginateOptions`, `PageEndpoint`, `PageRequest`, `PageOf`, - `PageResponse`: [pagination](#pagination). -- `plugin`, `Plugin` (and the `Plugin.*` helper types), `PluginContext`, - `PluginExitContext`: - [writing plugins](#writing-plugins). -- Option and result types, for wrapping the client in your own functions: - `RequestOptions`, `NoBodyRequestOptions`, `BaseOptions`, `BodyOptions`, - `ParamsOption`, `QueryInput`, `QueryOf`, `QueryValue`, `AnySchema`, - `Args`, `Success`, `ResponseMode`, `CallError`, `CallServices`, - `CallEffect`, - `NoBodyMethod`, `BodyMethod`, `RequestMethod`, `PathParamNames`, - `PathParams`, `PathParamValue`. `CallEffect` types a function that - returns a call; to take a call as an argument, accept any - `Effect.Effect`. - -`@monarcode/effetch/plugins` ([plugins](#plugins)): - -- `bearer`, `BearerOptions`, `BearerPlugin`, `TokenSource`, `TokenValue`, - `RefreshSource`. -- `logger`, `LoggerOptions`, `LoggerPlugin`. -- `consoleLogger`, `ConsoleLoggerOptions`, `ConsoleLoggerSettings`, - `ConsoleLoggerPlugin`, `ConsoleLoggerDetail`, `ConsoleLoggerRedact`, - `ConsoleLoggerCall`, `ConsoleLoggerColor`. -- `retry`, `RetryOptions`, `RetryPlugin`, `RetryBudgetOptions`, - `RetryBudgetPlugin`. -- `timeout`, `TimeoutOptions`, `TimeoutPlugin`, `TimeoutError`. - -`@monarcode/effetch/test`, as the `FetchTest` namespace -([testing](#testing)): - -- `layer`, `LayerOptions`, `Handler`, `HandlerServices`. -- `respond`, `RespondRequest`, `RespondResult`, `TestEvent`, `RespondOptions`, - `RespondServices`, `RouteParams`, `RequestBody`, `RequestQuery`, - `QueryParams`, `TestEndpoint`. -- `reply`, `Reply`, `ReplyOptions`. -- `fail`, `FailBody`, `FailServices`. -- `requests`, `Recorder`, `SentRequest`. +[Platform notes](https://effetch.pages.dev/docs/platforms) first. + +## Guides + +- [Clients](https://effetch.pages.dev/docs/clients): declare a client, configure it and + provide it. +- [Calls](https://effetch.pages.dev/docs/calls): methods, parameters, bodies, uploads and + responses. +- [Errors](https://effetch.pages.dev/docs/errors): what a call can fail with, and how to + catch and type each error. +- [Plugins](https://effetch.pages.dev/docs/plugins): auth, retries, timeouts and logging, and + writing your own. +- [Endpoints](https://effetch.pages.dev/docs/endpoints): save routes with their schemas and + share them as a service. +- [Streaming responses](https://effetch.pages.dev/docs/streaming) and + [Pagination](https://effetch.pages.dev/docs/pagination). +- [Structure an app](https://effetch.pages.dev/docs/structuring-an-app). +- [Testing](https://effetch.pages.dev/docs/testing): test calls against a fake backend made + from your endpoints. +- [Platform notes](https://effetch.pages.dev/docs/platforms): browsers and React Native. +- [Coming from axios or ky](https://effetch.pages.dev/docs/coming-from-axios-or-ky). +- [Upgrade from 0.1.0-rc.3](https://effetch.pages.dev/docs/upgrading). +- [Reference](https://effetch.pages.dev/docs/reference): the entry points, and + [Limitations](https://effetch.pages.dev/docs/reference/limitations). ## Examples diff --git a/package.json b/package.json index 50ad067..dd6da78 100644 --- a/package.json +++ b/package.json @@ -11,7 +11,7 @@ "react-native", "schema" ], - "homepage": "https://github.com/monarcode/effetch#readme", + "homepage": "https://effetch.pages.dev/docs", "bugs": { "url": "https://github.com/monarcode/effetch/issues" }, diff --git a/scripts/smoke.sh b/scripts/smoke.sh index aacdd19..f3cf55f 100755 --- a/scripts/smoke.sh +++ b/scripts/smoke.sh @@ -610,7 +610,8 @@ export const isHttp = (u: unknown): u is HttpError => u instanceof HttpError; export type Api = Http.Client; export type Remote = import("@monarcode/effetch").Client; TS -# The command the README documents, without reaching the registry. +# The command the upgrade guide (/docs/upgrading) documents, without reaching +# the registry. npx --offline -p @monarcode/effetch effetch-migrate legacy >/dev/null if grep -q '\* as Http from\|{ HttpError, make' legacy/api.ts; then echo "✗ effetch-migrate left rc.3-style imports in legacy/api.ts:" >&2 diff --git a/site/content/docs/(latest)/calls/body.mdx b/site/content/docs/(latest)/calls/body.mdx index 4a60649..28a4714 100644 --- a/site/content/docs/(latest)/calls/body.mdx +++ b/site/content/docs/(latest)/calls/body.mdx @@ -2,3 +2,70 @@ title: Send a body description: Send JSON, form data, text or bytes, encoded with a schema or as is. --- + +Send a request body with `post`, `put`, `patch` or `del`. Effetch sends the +`body` according to its type, and an `input` schema types and encodes it. + +## Send JSON or a form + +The following calls send a body encoded with an `input` schema, a plain JSON +body, and a `FormData` you build yourself: + +```ts +import * as Schema from "effect/Schema"; + +import type { Fetch } from "@monarcode/effetch"; + +declare const api: Fetch.Client; + +const Todo = Schema.Struct({ + id: Schema.Finite, + title: Schema.String, + done: Schema.Boolean, + due: Schema.Date, +}); +const NewTodo = Schema.Struct({ title: Schema.String, due: Schema.Date }); + +export const create = api.post("/todos", { + input: NewTodo, + body: { title: "Write docs", due: new Date() }, + output: Todo, +}); + +export const complete = api.patch("/todos/:id", { + params: { id: 1 }, + body: { done: true }, + output: Todo, +}); + +export const upload = (file: Blob) => { + const form = new FormData(); + form.append("file", file); + return api.post("/uploads", { body: form }); +}; +``` + +## How a body is sent + +A `body` is sent according to its type: + +- an `HttpBody`, a string, an `ArrayBuffer` or typed array, a `Blob` or + `File`, `FormData` and `URLSearchParams` are sent as they are; +- anything else is sent as JSON. + +## Encode the body with a schema + +Add an `input` schema, and `body` is typed by it and encoded with it before +it's sent as JSON. In `create`, `due` is a `Date` in your code and an ISO +string on the wire. + +To send a typed body as a form instead, such as a file upload, see +[Upload files](/docs/calls/uploads). + +## What's next + +- [Upload files](/docs/calls/uploads): send a typed body as + `multipart/form-data`. +- [Read the response](/docs/calls/responses): decode what the server sends + back. +- [Call options](/docs/calls/options): look up every option a call takes. diff --git a/site/content/docs/(latest)/calls/http-client.mdx b/site/content/docs/(latest)/calls/http-client.mdx index 72421fc..6cc1b0a 100644 --- a/site/content/docs/(latest)/calls/http-client.mdx +++ b/site/content/docs/(latest)/calls/http-client.mdx @@ -1,4 +1,42 @@ --- -title: Use HttpClient directly -description: Use Effect's HttpClient for what the methods don't cover. +title: When the methods aren't enough +description: Choose the method at runtime, read a stream, or use the HttpClient underneath a client. --- + +When the methods aren't enough, pick a method at runtime with `api.request`, +read a stream with `api.sse` or `api.ndjson`, or use the `HttpClient` +underneath the client. + +## Choose the method at runtime + +When the method is only known at runtime, use `api.request`. It takes the +method as its first argument, before the path and the options: + +```ts +import type * as HttpMethod from "effect/http/HttpMethod"; + +import type { Fetch } from "@monarcode/effetch"; + +declare const api: Fetch.Client; + +export const send = (method: HttpMethod.HttpMethod, path: string) => + api.request(method, path); +``` + +## Read a stream of events or lines + +When the response is a stream of events or lines, use `api.sse` or +`api.ndjson`. See [Streaming responses](/docs/streaming). + +## Use the underlying HttpClient + +When you need something the methods don't do, use `api.httpClient`. It's the +configured `HttpClient` underneath, with the base URL, the default headers and +the plugins, but no status check and no decoding. + +## What's next + +- [Streaming responses](/docs/streaming): read Server-Sent Events and + newline-delimited JSON. +- [Call errors](/docs/errors): see what can go wrong in a call. +- [Call options](/docs/calls/options): look up every option the methods take. diff --git a/site/content/docs/(latest)/calls/index.mdx b/site/content/docs/(latest)/calls/index.mdx index a186648..bd2baac 100644 --- a/site/content/docs/(latest)/calls/index.mdx +++ b/site/content/docs/(latest)/calls/index.mdx @@ -2,3 +2,22 @@ title: Methods description: Call a route with get, head, options, post, put, patch or del. --- + +With a client in hand, every call is one method: you pass the path and an +object of options, and get an Effect back. + +## Pick a method + +A client has a method for each HTTP method: + +- `get`, `head` and `options` send no body. +- `post`, `put`, `patch` and `del` can send one. It's `del` because `delete` + is a reserved word. + +## What's next + +- [Path and query parameters](/docs/calls/parameters): fill in the path and + build a query. +- [Send a body](/docs/calls/body): send JSON, forms, text or bytes. +- [Read the response](/docs/calls/responses): decode what comes back. +- [Call options](/docs/calls/options): look up every option a call takes. diff --git a/site/content/docs/(latest)/calls/options.mdx b/site/content/docs/(latest)/calls/options.mdx index 7ed6dba..85f697b 100644 --- a/site/content/docs/(latest)/calls/options.mdx +++ b/site/content/docs/(latest)/calls/options.mdx @@ -2,3 +2,24 @@ title: Call options description: Look up an option a call accepts. --- + +Every method takes the path and an object of options. This page lists every +option a call accepts. + +## Options + +The following options control how a call builds its request and reads its +response: + +| Option | What it does | +| -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `params` | Values for the path's `:params`. Required, with exactly those names, when the path has any; not allowed otherwise. Values are URI-encoded. | +| `query` | An object of query parameters. Arrays repeat the key, and `null` and `undefined` are dropped. | +| `headers` | Headers for this call. They win over the client's, and over the body's `content-type`. | +| `body` | Sent by its type: `HttpBody`, string, `ArrayBuffer` and typed arrays, `Blob`/`File`, `FormData` and `URLSearchParams` as they are, anything else as JSON. | +| `input` | A schema `body` is encoded with. `body` is then typed by it. Sent as JSON, or as `multipart/form-data` when wrapped in `Fetch.multipart` (see [Upload files](/docs/calls/uploads)). | +| `output` | A schema the 2xx body is decoded with: read as JSON, or as text with `Fetch.text()` and bytes with `Fetch.bytes()`. The call then sends a matching `Accept` header (unless you set `accept`). Without it, the call succeeds with the raw `HttpClientResponse`. See [Read the response](/docs/calls/responses). | +| `responseMode` | `"decoded-and-response"` makes the call succeed with `[value, response]`, to read the status and headers too. Defaults to `"decoded"`, the value alone. | +| `error` | A schema for the body of error responses, replacing the client's `defaultError`. | +| `statusErrors` | Your own errors for error responses, by status. See [Errors by status](/docs/errors/status-errors). | +| `plugins` | Plugin overrides for this call (see [Change plugins for one call](/docs/plugins/per-call)). | diff --git a/site/content/docs/(latest)/calls/parameters.mdx b/site/content/docs/(latest)/calls/parameters.mdx index d662dd4..72eed97 100644 --- a/site/content/docs/(latest)/calls/parameters.mdx +++ b/site/content/docs/(latest)/calls/parameters.mdx @@ -2,3 +2,55 @@ title: Path and query parameters description: Fill in a path's parameters and build a query. --- + +Fill in a path's `:name` parameters from `params`, and build the query string +from a plain `query` object. + +## Fill in path parameters and a query + +The following calls fill in an `:id` parameter, and send a query with a +number, a repeated key and a dropped value: + +```ts +import * as Schema from "effect/Schema"; + +import type { Fetch } from "@monarcode/effetch"; + +declare const api: Fetch.Client; + +const Todo = Schema.Struct({ id: Schema.Finite, title: Schema.String }); + +// GET /todos/1 +export const one = api.get("/todos/:id", { params: { id: 1 }, output: Todo }); + +// GET /todos?page=1&tags=work&tags=home +export const some = api.get("/todos", { + query: { page: 1, tags: ["work", "home"], search: undefined }, + output: Schema.Array(Todo), +}); +``` + +## Path parameters + +Every `:name` in a path is a parameter, filled in from `params`. When a path +has parameters, `params` is required, with exactly those names, and when it +has none, `params` isn't allowed. Effetch URI-encodes the values for you. + +## Query parameters + +`query` is a plain object. Arrays repeat the key, and `null` and `undefined` +are dropped, so you can pass optional filters as they are. + +With Effect 4.1 or later, a value can also be `Redacted`, such as +`Redacted.make(apiKey)`: it's sent as its value, and Effect keeps it out of +its own logs and traces. + +To type an endpoint's query and send values such as dates, give the endpoint +a schema for it. See [Typed query parameters](/docs/endpoints/typed-query). + +## What's next + +- [Send a body](/docs/calls/body): send data with `post`, `put` and `patch`. +- [Read the response](/docs/calls/responses): decode the body with a schema. +- [Typed query parameters](/docs/endpoints/typed-query): type a query with a + schema. diff --git a/site/content/docs/(latest)/calls/responses.mdx b/site/content/docs/(latest)/calls/responses.mdx index d31b0b6..f865c96 100644 --- a/site/content/docs/(latest)/calls/responses.mdx +++ b/site/content/docs/(latest)/calls/responses.mdx @@ -2,3 +2,132 @@ title: Read the response description: Decode the body with a schema, or read text, bytes or the whole response. --- + +Decode a response body with a schema, read it as text or bytes, or read the +status and headers next to the decoded body. + +## Decode the body with a schema + +Give a call an `output` schema, and the response body is decoded with it. The +call succeeds with the decoded value, or fails with `DecodeError` if the body +doesn't match. It also sends `Accept: application/json`, unless you set an +`accept` header yourself. + +Without `output`, the call succeeds with the raw `HttpClientResponse`. That's +handy when you only care that the call worked, or want to read the body +yourself: + +```ts +import * as Schema from "effect/Schema"; + +import type { Fetch } from "@monarcode/effetch"; + +declare const api: Fetch.Client; + +// No output: succeeds with the HttpClientResponse. +export const remove = api.del("/todos/:id", { params: { id: 1 } }); + +// Nothing to decode: an empty body (204, HEAD) decodes as JSON null. +export const archive = api.post("/todos/:id/archive", { + params: { id: 1 }, + output: Schema.Void, +}); +``` + + + Use `Schema.Finite` rather than `Schema.Number` for numbers. Responses are + decoded with Effect's JSON codec, where `Schema.Number` also decodes the + strings `"NaN"`, `"Infinity"` and `"-Infinity"`, and encodes those values back + to strings. `Schema.Finite` accepts every JSON number and rejects the rest. + + +## Read text or bytes + +`output` reads the body as JSON. For other bodies, wrap the schema: + +- `Fetch.text()` reads the body as a string, as it was sent. +- `Fetch.text(schema)` reads a single value, such as a count or a status: it + trims the text, then decodes it with a schema whose encoded side is a + string, such as `Schema.NumberFromString`. +- `Fetch.bytes()` reads the body as a `Uint8Array`, a copy of the body, for + images, PDFs and other binary bodies. + +The call sends a matching `Accept` header: `text/*, */*;q=0.1` for text, and +`*/*` for bytes, unless you set one. + +The following program reads a CSV export as text, a count as a number, and a +PDF as bytes: + +```ts +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import { Fetch } from "@monarcode/effetch"; + +declare const api: Fetch.Client; + +export const program = Effect.gen(function* () { + const csv = yield* api.get("/export.csv", { output: Fetch.text() }); + const count = yield* api.get("/todos/count", { + output: Fetch.text(Schema.NumberFromString), + }); + const pdf = yield* api.get("/invoices/:id", { + params: { id: 7 }, + output: Fetch.bytes(), + }); + // In a browser, Node, Bun or Deno. React Native's Blob doesn't take arrays. + return { csv, count, pdf: new Blob([pdf], { type: "application/pdf" }) }; +}); +``` + +They work wherever `output` does, endpoints included. + +- An empty body is `""` for `Fetch.text()` and a `Uint8Array` of length 0 for + `Fetch.bytes()`. For `Fetch.text(schema)`, it fails with `DecodeError`, as + for JSON. +- A body that can't be read, or doesn't match the schema, fails with + `DecodeError`. +- Error responses are still read as JSON for `error` and `statusErrors`. +- Pass the schema they return to `output` as it is. A schema built around it, + such as with `Schema.NullOr`, is read as JSON again. + +## Read the body and the response + +To read the status or headers next to the decoded body, such as a total count +or an `ETag`, set `responseMode: "decoded-and-response"`. The call succeeds +with a pair: + +```ts +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import type { Fetch } from "@monarcode/effetch"; + +declare const api: Fetch.Client; + +const Todo = Schema.Struct({ id: Schema.Finite, title: Schema.String }); + +export const page = Effect.gen(function* () { + const [todos, response] = yield* api.get("/todos", { + query: { page: 1 }, + output: Schema.Array(Todo), + responseMode: "decoded-and-response", + }); + return { todos, total: Number(response.headers["x-total-count"]) }; +}); +``` + +- It's allowed on calls, on endpoint definitions, and on each call of an + endpoint, where the call's own mode wins. +- Without `output`, both items are the response. +- The body has already been read: use the decoded value. +- The default, `"decoded"`, gives the decoded body alone. + +## What's next + +- [Call errors](/docs/errors): handle `DecodeError` and the other ways a call + fails. +- [Errors by status](/docs/errors/status-errors): turn error responses into + your own errors. +- [Streaming responses](/docs/streaming): read Server-Sent Events and + newline-delimited JSON. diff --git a/site/content/docs/(latest)/calls/uploads.mdx b/site/content/docs/(latest)/calls/uploads.mdx index 3de267c..59b790b 100644 --- a/site/content/docs/(latest)/calls/uploads.mdx +++ b/site/content/docs/(latest)/calls/uploads.mdx @@ -2,3 +2,173 @@ title: Upload files description: Upload files with a typed multipart body. --- + +Upload files with a body that's typed and checked by a schema, as for JSON, +then sent as `multipart/form-data`. + +## Send a multipart body + +To upload files, wrap the `input` schema in `Fetch.multipart`, and use +`Fetch.UploadFile` for a file field: + +```ts +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import { Fetch } from "@monarcode/effetch"; + +const Document = Schema.Struct({ id: Schema.String }); + +export const uploadDocument = Fetch.endpoint("POST /documents", { + input: Fetch.multipart( + Schema.Struct({ + file: Fetch.UploadFile, + kind: Schema.Literals(["PASSPORT", "DRIVERS_LICENSE"]), + pages: Schema.optional(Schema.Finite), + }), + ), + output: Document, +}); + +class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.example.com", +}) {} + +class DocumentApi extends Fetch.Endpoints()("DocumentApi", Api, { + upload: uploadDocument, +}) {} + +// In a browser, `file` comes from an . +export const upload = (file: File) => + Effect.gen(function* () { + const documents = yield* DocumentApi; + return yield* documents.upload({ body: { file, kind: "PASSPORT" } }); + }); +``` + +## Files on each platform + +`Fetch.UploadFile` takes the files each platform can send: + +- in browsers, Node, Bun and Deno, a `Blob` or `File`; +- in React Native, the `{ uri, name, type }` object its pickers give, typed + `Fetch.NativeFile`. `uri` and `name` are required: a server only treats a + part as a file when it has a file name. `type` is optional, and a file + without one is sent as `application/octet-stream`. + +Use `Fetch.UploadFile` rather than `Schema.File`. `Schema.File` only takes a +`File`, not the `{ uri, name, type }` objects React Native's pickers give, +and `FetchTest` can't read it back from a form. + +## Send a file from React Native + +In React Native, send a `NativeFile`, not a `Blob`: React Native's `fetch` +reads a form's files from disk by `uri`, and can't send a `Blob` in a form. + +The following example builds a `NativeFile` from an image picker's asset: + +```ts +import type { Fetch } from "@monarcode/effetch"; + +// From expo-image-picker, for example +declare const asset: { + readonly uri: string; + readonly fileName?: string | null; + readonly mimeType?: string; +}; + +export const photo: Fetch.NativeFile = { + uri: asset.uri, + name: asset.fileName ?? "photo.jpg", + type: asset.mimeType, +}; +``` + +## How fields become form parts + +Effetch turns the schema's fields into form parts as follows: + +- strings as they are; numbers, booleans and bigints as strings; a `Date` as + its ISO string; +- a file as a file part; +- a list as one part per item, under the same name; +- `null` and `undefined` left out. + +A form can't hold a nested object or a list of lists, so TypeScript rejects +most schemas that have one, and a value that has one makes the call die. To +send one, encode it to a string in the schema, such as +`meta: Schema.fromJsonString(Meta)`. + +## Check a file's size + +To check a file's size, add a check to `Fetch.UploadFile`. A `NativeFile` has +no size until it's read, so the check only looks at a `Blob`: + +```ts +import * as Schema from "effect/Schema"; + +import { Fetch } from "@monarcode/effetch"; + +export const SmallFile = Fetch.UploadFile.check( + Schema.makeFilter( + (file) => !(file instanceof Blob) || file.size < 10_000_000, + { expected: "a file under 10 MB" }, + ), +); +``` + +## Headers, errors and where it works + +The following details cover the request's headers, how a bad body fails, and +where multipart bodies work. + + + + +- The request sets no `Content-Type`, so the platform adds the multipart + boundary. A `content-type` header from the call, the endpoint or the client + is removed, for any `FormData` body. +- The request sets no `Content-Type` before your plugins run. A plugin's + `onRequest` that sets one replaces the boundary, so leave it out for forms. +- A body that doesn't match the schema, or a value a form can't hold, makes + the call die with an `Invalid request body:` defect, as for JSON (see + [Logging and defects](/docs/errors/logging-and-defects)). So does a + `{ uri, name, type }` file outside React Native, where `FormData` would send + `"[object Object]"`, or in a field that isn't a `Fetch.UploadFile`. +- `Fetch.UploadFile` in an `input` schema without `Fetch.multipart` makes the + call die too: a file has no JSON form. +- It works wherever `input` does: on methods such as `api.post`, on endpoints, + and in `api.sse` and `api.ndjson`. +- `Fetch.multipart` returns the schema, marked. Add checks or annotations to + it as you like. A schema built around it, such as with `Schema.NullOr`, is + sent as JSON again. +- A field's encoded value must be a string, number, boolean, bigint, `Date`, + file, `null` or `undefined`, or a list of them. A schema such as + `Schema.DateTimeUtc` or `Schema.URL`, which encodes to an object, needs a + string form first, such as `Schema.DateTimeUtcFromString`. +- [`FetchTest`](/docs/testing) reads the form back into the body a handler + gets, decoded with the schema, with files as `File`s. In Node, test with a + `Blob` or `File`, since a `{ uri, name, type }` file only works in React + Native. +- A form loses some of what the schema encodes, so `FetchTest` reads it back + as best it can: + - A `null` or `undefined` field and an empty list are left out. Such a + field comes back missing when it's optional. When it's required, it + comes back as `null` if it takes `null`, then as `[]` if it's a list, + then as `undefined`. + - Every part is a string. In a field that takes `null`, the string + `"null"` comes back as `null`, and in + `Schema.Union([Schema.String, Schema.Finite])` the string `"12"` comes + back as the number `12`. +- A `FormData` you build yourself still works as a `body` without `input`. + + + + +## What's next + +- [Send a body](/docs/calls/body): send JSON and other bodies. +- [Test with a fake backend](/docs/testing): read uploaded forms back in + tests with `FetchTest`. +- [Logging and defects](/docs/errors/logging-and-defects): see why a bad body + makes the call die. diff --git a/site/content/docs/(latest)/clients/configuration.mdx b/site/content/docs/(latest)/clients/configuration.mdx index 974ba16..3c8ed7a 100644 --- a/site/content/docs/(latest)/clients/configuration.mdx +++ b/site/content/docs/(latest)/clients/configuration.mdx @@ -2,3 +2,53 @@ title: Client configuration description: Look up an option a client accepts. --- + +This page lists the options you can pass when you declare a client. The +config of `Fetch.Service` takes the same options as `Fetch.make` (see +[Fetch.Service or Fetch.make](/docs/clients/service-or-make)). + +## Example + +Here's a client with all of the options: + +```ts +import * as Config from "effect/Config"; +import * as Schema from "effect/Schema"; + +import { Fetch } from "@monarcode/effetch"; +import { bearer, logger, retry, timeout } from "@monarcode/effetch/plugins"; + +const ApiError = Schema.Struct({ code: Schema.String, message: Schema.String }); + +class SessionExpired extends Schema.TaggedError()( + "SessionExpired", + { message: Schema.String }, +) {} + +const session: { accessToken?: string } = {}; + +export class Api extends Fetch.Service()("Api", { + baseUrl: Config.String("API_URL"), + headers: { "x-client": "web" }, + defaultError: ApiError, + statusErrors: { 401: SessionExpired }, + plugins: [ + logger(), + retry(), + timeout({ duration: "10 seconds" }), + bearer({ token: () => session.accessToken }), + ], +}) {} +``` + +## Options + +Every option is optional: + +| Option | What it's for | +| -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `baseUrl` | Where the API lives. It's put in front of every path that isn't a full `http(s)://` URL. Pass a string, or an Effect that's run once when the client is built, such as a `Config`. It can't contain a query string or a fragment. | +| `headers` | Headers sent with every request. A call's header with the same name wins. `content-type` and `content-length` are ignored here, since they come from each body. | +| `defaultError` | A schema for the body of the API's error responses (see [Typed error bodies](/docs/errors/error-bodies)). | +| `statusErrors` | Your own errors for error responses, by status, for every call (see [Errors by status](/docs/errors/status-errors)). | +| `plugins` | Behavior every call goes through, outermost first (see [Built-in plugins](/docs/plugins)). | diff --git a/site/content/docs/(latest)/clients/derived.mdx b/site/content/docs/(latest)/clients/derived.mdx index 154f24f..ca5ebfa 100644 --- a/site/content/docs/(latest)/clients/derived.mdx +++ b/site/content/docs/(latest)/clients/derived.mdx @@ -2,3 +2,44 @@ title: Derive a client description: Make a client from another, with a different base URL or one more header. --- + +This page shows how to make a second client from a first one, for the same +client with a different base URL, such as a second API version, or with one +more header. + +## Spread the first client's config + +Spread the first class's `config` into a second class. The second class +keeps the plugins, `defaultError` and `statusErrors`, so its client has the +same type: + +```ts +import * as Schema from "effect/Schema"; + +import { Fetch } from "@monarcode/effetch"; +import { retry } from "@monarcode/effetch/plugins"; + +export class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.example.com/v1", + defaultError: Schema.Struct({ code: Schema.String }), + plugins: [retry()], +}) {} + +export class ApiV2 extends Fetch.Service()("ApiV2", { + ...Api.config, + baseUrl: "https://api.example.com/v2", +}) {} +``` + +## Keep the first client's headers + +When you set `headers`, `Api.config.headers` is replaced, not merged. To +keep the first client's headers, spread them too, as in +`headers: { ...Api.config.headers, "x-client": "web" }`. + +## What's next + +- [Client configuration](/docs/clients/configuration): look up the options + you can override. +- [Structure an app](/docs/structuring-an-app): organize an app that talks + to several backends. diff --git a/site/content/docs/(latest)/clients/index.mdx b/site/content/docs/(latest)/clients/index.mdx index 376a211..93f6ee3 100644 --- a/site/content/docs/(latest)/clients/index.mdx +++ b/site/content/docs/(latest)/clients/index.mdx @@ -2,3 +2,78 @@ title: Declare a client description: Declare a client as an Effect service with Fetch.Service. --- + +This page shows how to declare a client with `Fetch.Service` and use it +anywhere in your app. + +A client holds everything a backend's calls have in common: where the +backend lives, the headers every request needs, the shape of its errors and +the plugins every call goes through. You declare it once and share it with +the rest of your app. + +## Declare the client + +`Fetch.Service` declares a client as an Effect service, in one class: + +```ts +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import { Fetch } from "@monarcode/effetch"; + +const Todo = Schema.Struct({ id: Schema.Finite, title: Schema.String }); + +export class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.example.com", +}) {} + +// Anywhere in your app +export const program = Effect.gen(function* () { + const api = yield* Api; + return yield* api.get("/todos/:id", { params: { id: 1 }, output: Todo }); +}); +``` + +## What the class gives you + +The class gives you three things: + +- **`Api` is the service.** `yield* Api` gives the client, typed from the + config. +- **`Api.layer` builds the client.** It needs an `HttpClient`, plus + whatever the `baseUrl` Effect and the plugins need. Every layer that + depends on it in one layer graph gets the same client. +- **`Api.config` is the config you passed**, frozen. You can read it when + the module loads, before any layer is built, for example to get the + `defaultError` and `statusErrors` schemas. + +## Type the client + +Your client's type is `Effect.Success`. It includes your +plugins and your `defaultError`. Use it wherever you need to type a client, +such as a function parameter. + +`Fetch.Client` is the type of a client without plugins, and yours won't fit +it. + +## Call from anywhere + +Calls need nothing from the environment. The client holds on to the +`HttpClient`, the base URL and any services its plugins need. Its calls +only need the services of their own schemas, if any, so they run anywhere: +in a service, in a query function, or with `Effect.runPromise`. + +## Give each client its own id + +Two classes with the same id are the same service, so give each client its +own id. `Fetch.isService(value)` tells a class made by `Fetch.Service` +apart from any other value. + +## What's next + +- [Client configuration](/docs/clients/configuration): look up the options + the config takes. +- [Provide the client](/docs/clients/providing): give `Api.layer` the + `HttpClient` it needs, and run your program. +- [Fetch.Service or Fetch.make](/docs/clients/service-or-make): find out + when to build a client without the class. diff --git a/site/content/docs/(latest)/clients/providing.mdx b/site/content/docs/(latest)/clients/providing.mdx index fe66072..45395c1 100644 --- a/site/content/docs/(latest)/clients/providing.mdx +++ b/site/content/docs/(latest)/clients/providing.mdx @@ -2,3 +2,73 @@ title: Provide the client description: Give a program the HttpClient that the client's layer needs. --- + +This page shows how to give `Api.layer` the `HttpClient` it needs, so you +can run a program that uses your client. + +## Provide an HttpClient where you run the program + +`Api.layer` needs an `HttpClient`. Provide one where you run your program, +usually next to the other layers of your app: + +```ts +import * as Effect from "effect/Effect"; +import * as FetchHttpClient from "effect/http/FetchHttpClient"; +import * as Layer from "effect/Layer"; + +import { Fetch } from "@monarcode/effetch"; + +export class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.example.com", +}) {} + +export const ApiLive = Api.layer.pipe(Layer.provide(FetchHttpClient.layer)); + +export const program = Effect.gen(function* () { + const api = yield* Api; + return yield* api.get("/health"); +}); + +export const runnable = program.pipe(Effect.provide(ApiLive)); +``` + +Keeping the `HttpClient` out of `Api.layer` is what lets tests swap in a +fake one. + +## Build the HttpClient into the layer + +If you'd rather have `Api.layer` provide the `HttpClient` too, override the +layer in the class: + +```ts +import * as FetchHttpClient from "effect/http/FetchHttpClient"; +import * as Layer from "effect/Layer"; + +import { Fetch } from "@monarcode/effetch"; + +export class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.example.com", +}) { + static override readonly layer = super.layer.pipe( + Layer.provide(FetchHttpClient.layer), + ); +} +``` + +An override can need less than the original layer, but not more, and can't +add an error. + + + The override builds the real `HttpClient` into `Api.layer`, so a test can no + longer swap in a fake one: `FetchTest.layer` provided under it is ignored, and + requests go to the network. If you test with `Api.layer`, keep it as it is and + export a separate `ApiLive`, as in the first example. + + +## What's next + +- [Test with a fake backend](/docs/testing): provide a fake `HttpClient` + instead of the real one. +- [Derive a client](/docs/clients/derived): make a second client from the + first one's config. +- [Methods](/docs/calls): make calls with the client. diff --git a/site/content/docs/(latest)/clients/service-or-make.mdx b/site/content/docs/(latest)/clients/service-or-make.mdx index dd68a25..c9d1ba0 100644 --- a/site/content/docs/(latest)/clients/service-or-make.mdx +++ b/site/content/docs/(latest)/clients/service-or-make.mdx @@ -2,3 +2,81 @@ title: Fetch.Service or Fetch.make description: Choose between declaring a client as a service and building one with Fetch.make. --- + +This page explains how `Fetch.Service` and `Fetch.make` relate, and helps +you choose between them. + +## How they relate + +`Fetch.make` is the function underneath `Fetch.Service`: it takes the same +config and returns an Effect that builds the client. Both give you the same +client, with the same calls and the same types. + +## Which one to use + +Use the class by default, and reach for `Fetch.make` when the class doesn't +fit: + +| Situation | Use | +| ---------------------------------------------------------------------------------- | --------------- | +| An app, with the client shared as a service | `Fetch.Service` | +| A config known when the module loads (a `baseUrl` Effect such as `Config` is fine) | `Fetch.Service` | +| Endpoints shared as a service with [`Fetch.Endpoints`](/docs/endpoints/services) | `Fetch.Service` | +| A script, a one-off program, or a quick test | `Fetch.make` | +| A config that comes from an Effect, such as headers read from a service | `Fetch.make` | +| A client made inside your own service's layer, or one per tenant at runtime | `Fetch.make` | + +## Fetch.make in a script + +In a script, use `Fetch.make` inline: + +```ts +import * as Effect from "effect/Effect"; +import * as FetchHttpClient from "effect/http/FetchHttpClient"; + +import { Fetch } from "@monarcode/effetch"; + +const program = Effect.gen(function* () { + const api = yield* Fetch.make({ baseUrl: "https://api.example.com" }); + return yield* api.get("/health"); +}); + +await Effect.runPromise(program.pipe(Effect.provide(FetchHttpClient.layer))); +``` + +## Fetch.make with a config from an Effect + +When the config itself comes from an Effect, call `Fetch.make` inside that +Effect and declare the service by hand: + +```ts +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import { Fetch } from "@monarcode/effetch"; + +class Tenant extends Context.Service()( + "Tenant", +) {} + +const makeApi = Effect.gen(function* () { + const tenant = yield* Tenant; + return yield* Fetch.make({ + baseUrl: "https://api.example.com", + headers: { "x-tenant": tenant.id }, + }); +}); + +export class Api extends Context.Service>()( + "Api", +) {} + +export const ApiLive = Layer.effect(Api)(makeApi); +``` + +## Related pages + +- [Declare a client](/docs/clients): declare a client with `Fetch.Service`. +- [Client configuration](/docs/clients/configuration): the options both + take. diff --git a/site/content/docs/(latest)/coming-from-axios-or-ky.mdx b/site/content/docs/(latest)/coming-from-axios-or-ky.mdx index 5a0ad8e..ff9d37a 100644 --- a/site/content/docs/(latest)/coming-from-axios-or-ky.mdx +++ b/site/content/docs/(latest)/coming-from-axios-or-ky.mdx @@ -2,3 +2,26 @@ title: Coming from axios or ky description: Map what you know from axios or ky to Effetch. --- + +If you've used axios or ky, most of what you know has a counterpart in +Effetch. The following table maps what you know from axios and ky to Effetch: + +| axios or ky | Effetch | +| ------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `axios.create`, `ky.create` | [`Fetch.Service`](/docs/clients), or [`Fetch.make`](/docs/clients/service-or-make) in a script | +| `ky.extend`, a client per API version | A second `Fetch.Service` from `{ ...Api.config, baseUrl }` (see [Derive a client](/docs/clients/derived)) | +| `baseURL`, `prefixUrl` | `baseUrl`, a string or an Effect such as a `Config` | +| `params`, `searchParams` | `query`, a plain object, or typed by an endpoint's [`query` schema](/docs/endpoints/typed-query) | +| Interceptors, `hooks.beforeRequest` and `hooks.afterResponse` | A [plugin](/docs/plugins/writing)'s `onRequest` and `onResponse` | +| `hooks.beforeError` | `Effect.mapError` on the call. A plugin's `onError` sees errors but can't change them | +| `retry`, `timeout` | The [`retry` and `timeout` plugins](/docs/plugins), which a call can turn off or adjust | +| ky's `totalTimeout` | `retry({ budget })`, or `Effect.timeout` around a call | +| `AbortController`, `signal` | Interruption: `Fiber.interrupt`, `Effect.race`, `Effect.timeout`. An interrupted call aborts its request | +| `validateStatus`, `throwHttpErrors: false` | `Effect.catchTag("HttpError", …)`, [`statusErrors`](/docs/errors/status-errors), or [`Fetch.catchStatus`](/docs/errors/catching#catch-a-status) and `Fetch.optional` | +| `error.response.data`, ky's `HTTPError` body | `HttpError.body`, decoded with `defaultError` or the call's `error` schema | +| `ky.get(url).json()`, `axios.get(url)` | `api.get(path, { output: Schema })`: the body is checked, not cast | +| `responseType: "text"` or `"arraybuffer"` | `output: Fetch.text()` or `Fetch.bytes()` (see [Read text or bytes](/docs/calls/responses#read-text-or-bytes)) | +| Reading the status and headers with the data | `responseMode: "decoded-and-response"` (see [Read the body and the response](/docs/calls/responses#read-the-body-and-the-response)) | +| `responseType: "stream"`, `onDownloadProgress` for events | [`api.sse` and `api.ndjson`](/docs/streaming) | +| A `FormData` body built by hand | `input: Fetch.multipart(schema)`, a typed body sent as a form (see [Upload files](/docs/calls/uploads)) | +| The `fetch` option or an `adapter` in tests | [`FetchTest`](/docs/testing), or any `HttpClient` layer | diff --git a/site/content/docs/(latest)/endpoints/calling.mdx b/site/content/docs/(latest)/endpoints/calling.mdx index c199c97..d563d2a 100644 --- a/site/content/docs/(latest)/endpoints/calling.mdx +++ b/site/content/docs/(latest)/endpoints/calling.mdx @@ -1,4 +1,134 @@ --- title: Call an endpoint -description: Bind endpoints to a client and call them. +description: Pass what changes on each call, and bind endpoints to a client with bind, bindAll or api.endpoint. --- + +This page shows you what to pass when you call an endpoint, and how to bind +endpoints to a client yourself when `Fetch.Endpoints` doesn't fit. + +## Pass what changes on each call + +What's fixed goes in the definition, and what changes goes in each call: + +| Defined once, on the endpoint | Passed with each call | +| --------------------------------------------------- | ------------------------- | +| `output`, `error`, `input`, `query`, `statusErrors` | `params`, `query`, `body` | +| `headers`, `responseMode`, `stream` | `headers`, `responseMode` | +| `plugins` (when binding) | `plugins` | + +A call follows these rules: + +- `users.get({ params: { id } })` sends exactly what + `api.get("/users/:id", { output: User, params: { id } })` does, and + returns the same Effect. +- `params` are required when the route's path has any, as with the methods. + An endpoint that needs nothing more is called with no arguments: + `users.list()`. +- With an `input` schema, `body` is required and typed by it. +- `GET`, `HEAD`, `OPTIONS` and `TRACE` endpoints take no `body` and no + `input`, and TypeScript rejects them. +- With a `query` schema, `query` is typed by it, and required when the + schema has required fields. See + [Typed query parameters](/docs/endpoints/typed-query). + +## Bind endpoints with bind and bindAll + +`Fetch.Endpoints` is built on two client methods, which you can also use +directly, such as inside your own service's layer: + +- **`api.bind(definition, options?)`** binds one definition. `options` are + the binding's `headers` and `plugins` overrides. +- **`api.bindAll(record)`** binds a record of definitions, each under its own + name. An entry can also be a `[definition, options]` pair, with the options + `api.bind` takes. Each endpoint has the type `api.bind` gives it. + +The following example binds the same two endpoints both ways: + +```ts +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import { Fetch } from "@monarcode/effetch"; +import { bearer } from "@monarcode/effetch/plugins"; + +const User = Schema.Struct({ id: Schema.Finite, name: Schema.String }); +const Session = Schema.Struct({ token: Schema.String }); + +const getUser = Fetch.endpoint("GET /users/:id", { output: User }); +const login = Fetch.endpoint("POST /auth/login", { output: Session }); + +class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.example.com", + plugins: [bearer({ token: "token" })], +}) {} + +export const endpoints = Effect.gen(function* () { + const api = yield* Api; + return { + getUser: api.bind(getUser), + login: api.bind(login, { plugins: { bearer: false } }), + }; +}); + +export const sameEndpoints = Effect.gen(function* () { + const api = yield* Api; + return api.bindAll({ + getUser, + login: [login, { plugins: { bearer: false } }], + }); +}); +``` + +## Define and bind in one step + +**`api.endpoint(route, definition)`** defines and binds in one step, where +you already have the client. Its definition can take `plugins` directly, +since it knows the client's plugins: + +```ts +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import { Fetch } from "@monarcode/effetch"; +import { bearer } from "@monarcode/effetch/plugins"; + +const Session = Schema.Struct({ token: Schema.String }); + +class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.example.com", + plugins: [bearer({ token: "token" })], +}) {} + +export const endpoints = Effect.gen(function* () { + const api = yield* Api; + return { + login: api.endpoint("POST /auth/login", { + output: Session, + plugins: { bearer: false }, + }), + }; +}); +``` + +## Choose between Fetch.endpoint and api.endpoint + +`api.bind(Fetch.endpoint(route, definition))` is the endpoint +`api.endpoint(route, definition)` makes, with the same type and the same +calls. Prefer `Fetch.endpoint` when: + +- endpoints should be listed next to their schemas, in a file with no client + (see + [A feature-sliced app](/docs/structuring-an-app#a-feature-sliced-app)); +- one definition serves several clients, such as staging and production; +- a tool works from your endpoints, and needs their routes and schemas + without a client, as `FetchTest` does (see + [Test with a fake backend](/docs/testing)). + +## What's next + +- [Typed query parameters](/docs/endpoints/typed-query): give an endpoint a + schema for its query. +- [Build an endpoint's URL](/docs/endpoints/urls): get the URL a call would + go to, without sending it. +- [Endpoints or methods](/docs/endpoints): decide which calls deserve an + endpoint. diff --git a/site/content/docs/(latest)/endpoints/defining.mdx b/site/content/docs/(latest)/endpoints/defining.mdx index c7788c6..6ee450a 100644 --- a/site/content/docs/(latest)/endpoints/defining.mdx +++ b/site/content/docs/(latest)/endpoints/defining.mdx @@ -2,3 +2,83 @@ title: Define endpoints description: Save a route with its schemas, defaults and overrides. --- + +This page shows you how to define an endpoint with `Fetch.endpoint`, how +its defaults combine with the client's and the call's, and which properties +you can read from it. + +## Define an endpoint + +`Fetch.endpoint` takes a route, the method and the path in one string, and +what every call to it shares. It needs no client, so you can define endpoints +next to their schemas: + +```ts +import * as Schema from "effect/Schema"; + +import { Fetch } from "@monarcode/effetch"; + +const User = Schema.Struct({ id: Schema.Finite, name: Schema.String }); +const NewUser = Schema.Struct({ name: Schema.String }); + +export const getUser = Fetch.endpoint("GET /users/:id", { output: User }); +export const listUsers = Fetch.endpoint("GET /users", { + output: Schema.Array(User), +}); +export const createUser = Fetch.endpoint("POST /users", { + input: NewUser, + output: User, +}); + +getUser.route; // "GET /users/:id" +getUser.output; // User +``` + +A definition is plain data: it holds the route, the schemas and the defaults, +but it can't make a call until it's bound to a client. To bind it, see +[Share endpoints as a service](/docs/endpoints/services). + +## Write the route + +The route is an uppercase method, one space, then a path that starts with `/` +or a full `http(s)://` URL. TypeScript checks it as you type: `"GTE /users"` +and `"get /users"` don't compile, and your editor suggests the methods. +`Fetch.endpoint` also throws on a malformed route, so a bad one fails as soon +as its module is imported. + +## Set defaults and overrides + +An endpoint's headers, plugin overrides and schemas combine with the +client's and the call's as follows: + +- **Headers.** A call's headers win over the endpoint's, which win over the + client's. A bound endpoint's headers are the binding's over the + definition's. Unlike the client's, an endpoint's headers can set + `content-type`. +- **Plugins.** A call's plugin override wins over the endpoint's (given when + binding, or to `api.endpoint`), and when both give options, they're + merged. An endpoint bound with `retry: false` can still be retried in one + call with `plugins: { retry: { times: 2 } }`. +- **Schemas** belong to the endpoint, and can't be changed per call. + +## Read an endpoint's properties + +Each endpoint also has `route`, `method` and `path` properties, for log labels +or cache keys. Plugins see the same route, as `ctx.route` (see +[Write a plugin](/docs/plugins/writing)). + +Its `output`, `error` and `input` properties are its schemas, for things like +decoding cached data or building test fixtures: + +- `output` and `input` are `undefined` when the endpoint has none. +- `error` is the schema error bodies are decoded with: the endpoint's, else + the client's `defaultError`, else `Schema.Unknown`. + +## What's next + +- [Share endpoints as a service](/docs/endpoints/services): bind your + definitions to a client and share them as a service. +- [Call an endpoint](/docs/endpoints/calling): see what goes in each call, + and other ways to bind. +- [Typed query parameters](/docs/endpoints/typed-query): give an endpoint a + schema for its query. diff --git a/site/content/docs/(latest)/endpoints/index.mdx b/site/content/docs/(latest)/endpoints/index.mdx index 6bc75fe..b60499f 100644 --- a/site/content/docs/(latest)/endpoints/index.mdx +++ b/site/content/docs/(latest)/endpoints/index.mdx @@ -2,3 +2,86 @@ title: Endpoints or methods description: Learn what endpoints add over methods, and when to use each. --- + +This page explains what an endpoint is, what it adds over the methods, and +how to choose between them for each call. + +The methods spell out a call's path and schemas where the call is made. +That's fine for a call made once. Once a call is made from several places, +you start repeating its path, its schemas and its rules, and a mistake in one +copy still compiles. An endpoint saves them once, and gives you a function to +call. + +## What endpoints add + +An HTTP call mixes two kinds of information: + +| Fixed by the API | Different on every call | +| ---------------------------------------------------- | ----------------------------------- | +| the route; the response, error and body schemas | path params, query values, the body | +| rules for that route, such as "login sends no token" | a one-off header or plugin override | + +With the methods, you write both at every call site. Three calls to +`GET /users/:id` repeat the path and the `User` schema three times, and a +mistake in one of them, such as the wrong schema or a forgotten +`bearer: false`, still compiles. An endpoint takes the first column once, when +it's defined, and only the second column when it's called. That gives you: + +- **One place per route.** A path or a schema changes in one line, and the + service that holds your endpoints lists the API you use. +- **Stricter types than a method can have.** A method only learns its HTTP + method and its `input` at the call, so it has to accept both ways. An + endpoint knows them up front: `body` is required when there's an `input` + (it's optional with `api.post`), a `GET` endpoint rejects a `body` at + compile time (`api.request("GET", …)` only dies at runtime), and the route + is checked as you type. +- **Defaults that can't be forgotten.** An endpoint's headers and plugin + overrides apply to every call. +- **A name instead of a URL.** Call sites read `users.get(…)`, and `route`, + `method` and `path` are there for query keys and log labels. + +Endpoints add no new behavior: a call goes through the same plugins, +decoding and errors as the method it stands for, so everything in +[Declare a client](/docs/clients), [Methods](/docs/calls), +[Call errors](/docs/errors) and [Built-in plugins](/docs/plugins) applies to +both. An endpoint is a saved +call, not a contract shared with a server. For that, use Effect's `HttpApi`. + +## When to use an endpoint + +Use an endpoint when a call: + +- is made from more than one place; +- has rules every call must follow, such as an auth exception or a content + type; +- sends a body with an `input` schema; +- belongs to a backend whose API you want listed in one place. + +## When to use a method + +Use a method for one-off calls, and for calls whose method or path is only +known at runtime. Mixing them is normal: keep the client next to its +endpoints, for the calls that aren't worth one. + +## Patterns to avoid + +Avoid the following: + +- **`api.endpoint(…)(…)` at a call site.** That's a method call written + twice: use the method. +- **Making or binding endpoints in code that runs on every request.** Do it + once, when the layer that holds them is built, as `Fetch.Endpoints` does. +- **Passing a bound endpoint's plugin overrides at every call.** A definition + can't hold them, since it doesn't know the client's plugins: give them once, + when binding, as in `api.bind(login, { plugins: { bearer: false } })`. +- **Spreading several groups of endpoints into one object.** When two use the + same name, the later one silently wins. Nest them instead: + `{ users, todos }`, or give each group its own `Fetch.Endpoints` class. + +## What's next + +- [Define endpoints](/docs/endpoints/defining): save a route with its + schemas and defaults. +- [Share endpoints as a service](/docs/endpoints/services): bind your + endpoints to a client once, in a layer. +- [Call an endpoint](/docs/endpoints/calling): see what each call takes. diff --git a/site/content/docs/(latest)/endpoints/meta.json b/site/content/docs/(latest)/endpoints/meta.json index 7c6c347..43c5272 100644 --- a/site/content/docs/(latest)/endpoints/meta.json +++ b/site/content/docs/(latest)/endpoints/meta.json @@ -1,4 +1,4 @@ { "title": "Endpoints", - "pages": ["index", "defining", "calling", "services", "typed-query", "urls"] + "pages": ["index", "defining", "services", "calling", "typed-query", "urls"] } diff --git a/site/content/docs/(latest)/endpoints/services.mdx b/site/content/docs/(latest)/endpoints/services.mdx index 41b4eb3..729355d 100644 --- a/site/content/docs/(latest)/endpoints/services.mdx +++ b/site/content/docs/(latest)/endpoints/services.mdx @@ -1,4 +1,107 @@ --- title: Share endpoints as a service -description: Expose a module's endpoints as a service. +description: Bind a record of endpoint definitions to a client once, and share them as an Effect service. --- + +This page shows you how to bind your endpoint definitions to a client with +`Fetch.Endpoints`, so code anywhere in your app can call them through one +service. + +## Declare the service + +`Fetch.Endpoints` binds a record of definitions to a client and shares them as +a service, the way `Fetch.Service` does for the client. It takes the +service's id, the client's service and the record: + +```ts +import * as Effect from "effect/Effect"; +import * as FetchHttpClient from "effect/http/FetchHttpClient"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; + +import { Fetch } from "@monarcode/effetch"; +import { bearer } from "@monarcode/effetch/plugins"; + +declare const readToken: () => Promise; + +const User = Schema.Struct({ id: Schema.Finite, name: Schema.String }); +const NewUser = Schema.Struct({ name: Schema.String }); +const Credentials = Schema.Struct({ + user: Schema.String, + password: Schema.String, +}); +const Session = Schema.Struct({ token: Schema.String }); + +const getUser = Fetch.endpoint("GET /users/:id", { output: User }); +const listUsers = Fetch.endpoint("GET /users", { output: Schema.Array(User) }); +const createUser = Fetch.endpoint("POST /users", { + input: NewUser, + output: User, +}); +const login = Fetch.endpoint("POST /auth/login", { + input: Credentials, + output: Session, +}); + +export class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.example.com", + plugins: [bearer({ token: () => readToken() })], +}) {} + +export class UserApi extends Fetch.Endpoints()("UserApi", Api, { + get: getUser, + list: listUsers, + create: createUser, + // A [definition, options] pair: logging in sends no token. + login: [login, { plugins: { bearer: false } }], +}) {} + +export const program = Effect.gen(function* () { + const users = yield* UserApi; + const ada = yield* users.create({ body: { name: "Ada" } }); + const page = yield* users.list({ query: { page: 2 } }); + const user = yield* users.get({ params: { id: ada.id } }); + return { page, user }; +}); + +export const AppLayer = UserApi.layer.pipe( + Layer.provideMerge(Api.layer), + Layer.provide(FetchHttpClient.layer), +); +``` + +## What the class gives you + +Like `Fetch.Service`, the class gives you three things: + +- **`UserApi` is the service.** `yield* UserApi` gives the endpoints, each + typed with the client's plugins, `defaultError` and `statusErrors`. +- **`UserApi.layer` binds them** to the client once, when it's built. It + needs the client's service, here `Api`. The client can also be a service + you wrote by hand. +- **`UserApi.definitions` is the record you passed**, frozen. You can read + it when the module loads. + +`Layer.provideMerge` keeps `Api` in the layer's output, so code can still +`yield* Api` for one-off calls. + +## Give options that depend on the client + +A definition doesn't know its client, so the following options depend on +the binding: + +- **Plugin overrides are given when binding,** as in the `login` pair in the + example, where they're checked against the client's plugins. A definition + takes no `plugins`. +- **A definition without an `error` schema** uses the `defaultError` of the + client it's bound to. +- **Headers can be given in both.** The binding's win over the definition's. + +## What's next + +- [Call an endpoint](/docs/endpoints/calling): see what each call takes, + and how to bind endpoints without a service. +- [Structure an app](/docs/structuring-an-app): decide where clients and + endpoints live as your app grows. +- [Test with a fake backend](/docs/testing): serve your endpoints from a + fake backend in tests. diff --git a/site/content/docs/(latest)/endpoints/typed-query.mdx b/site/content/docs/(latest)/endpoints/typed-query.mdx index 6f38bab..72a9158 100644 --- a/site/content/docs/(latest)/endpoints/typed-query.mdx +++ b/site/content/docs/(latest)/endpoints/typed-query.mdx @@ -1,4 +1,80 @@ --- title: Typed query parameters -description: Give an endpoint a schema for its query. +description: Give an endpoint a schema that types each call's query and encodes it before it's sent. --- + +This page shows you how to give an endpoint a `query` schema, how each field +is encoded into the URL, and what happens when a query doesn't match. + +## Add a query schema + +Give an endpoint a `query` schema, usually a `Schema.Struct`, and each call's +`query` is typed by it and encoded with it before it's sent. A `Schema.Class` +works too, called with an instance: + +```ts +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import { Fetch } from "@monarcode/effetch"; + +const Todo = Schema.Struct({ id: Schema.Finite, title: Schema.String }); + +const TodoFilters = Schema.Struct({ + done: Schema.optional(Schema.Boolean), + since: Schema.optional(Schema.Date), + pageSize: Schema.optional(Schema.Finite), +}).pipe(Schema.encodeKeys({ pageSize: "page_size" })); + +export const listTodos = Fetch.endpoint("GET /todos", { + query: TodoFilters, + output: Schema.Array(Todo), +}); + +class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.example.com", +}) {} + +export const program = Effect.gen(function* () { + const api = yield* Api; + const list = api.bind(listTodos); + // GET /todos?done=false&since=2026-01-01T00%3A00%3A00.000Z&page_size=20 + return yield* list({ + query: { done: false, since: new Date("2026-01-01"), pageSize: 20 }, + }); +}); +``` + +The schema is the endpoint's `query` property. `client.bind`, +`client.bindAll` and `Fetch.Endpoints` keep it, and `api.endpoint` takes one +too. + +## How each field is encoded + +The schema encodes the query as follows: + +- Each field is encoded to a string: a `Date` to its ISO string, a boolean to + `"true"` or `"false"`, a number to its digits. An array repeats the key. +- Rename keys with `Schema.encodeKeys`, as in the example. +- A field you leave out isn't sent, but a `null` is sent as the string + `"null"`, so prefer optional fields to nullable ones. +- A `Schema.Redacted` field is sent as its value and, with Effect 4.1 or + later, stays redacted in Effect's logs and traces. + +## Queries that don't match + +A query or a schema that can't be encoded fails early: + +- A query that doesn't match the schema, or a field that encodes to an + object, is a bug, not an error to handle: the call dies before anything is + sent. See [Logging and defects](/docs/errors/logging-and-defects). +- A schema with a field that has no string encoding, such as + `Schema.instanceOf(Uint8Array)`, throws when the endpoint is defined. + +## What's next + +- [Build an endpoint's URL](/docs/endpoints/urls): get the URL, query + included, without sending a request. +- [Call an endpoint](/docs/endpoints/calling): see everything a call takes. +- [Path and query parameters](/docs/calls/parameters): send a query from a + method call. diff --git a/site/content/docs/(latest)/endpoints/urls.mdx b/site/content/docs/(latest)/endpoints/urls.mdx index 806d721..2243725 100644 --- a/site/content/docs/(latest)/endpoints/urls.mdx +++ b/site/content/docs/(latest)/endpoints/urls.mdx @@ -1,4 +1,69 @@ --- title: Build an endpoint's URL -description: Get an endpoint's URL without sending a request. +description: Get the URL a call to an endpoint would go to, without sending a request. --- + +This page shows you how to get the URL an endpoint call would go to, as a +string, for a link, an `` source, or a cache key. + +## Get the URL + +`endpoint.url(options)` returns the URL a call with the same `params` and +`query` would go to. It works on a definition and on a bound endpoint: + +```ts +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import { Fetch } from "@monarcode/effetch"; + +const getFile = Fetch.endpoint("GET /files/:name", { + query: Schema.Struct({ download: Schema.optional(Schema.Boolean) }), +}); + +class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.example.com", +}) {} + +// "/files/report.pdf?download=true" +export const path = getFile.url({ + params: { name: "report.pdf" }, + query: { download: true }, +}); + +export const link = Effect.gen(function* () { + const api = yield* Api; + // "https://api.example.com/files/report.pdf?download=true" + return api.bind(getFile).url({ + params: { name: "report.pdf" }, + query: { download: true }, + }); +}); +``` + +## What the URL contains + +The URL contains the following: + +- On a bound endpoint, the URL starts with the client's `baseUrl`. +- On a definition from `Fetch.endpoint`, which has no client, it's the path + alone, unless the route is a full URL. That makes it a stable cache key + for one backend, whichever client calls it. +- The URL is built before plugins run, so anything a plugin adds, such as a + token in the query, isn't in it. + +## When url throws + +`url` throws when a path parameter is missing or the query doesn't match the +schema, as a call would die. It encodes the query synchronously, so on an +endpoint whose query schema needs services to encode, calling it doesn't +compile. + +## What's next + +- [Typed query parameters](/docs/endpoints/typed-query): see how the query + is encoded. +- [Write a plugin](/docs/plugins/writing): read the route a call goes to + from a plugin. +- [Call an endpoint](/docs/endpoints/calling): send the request the URL + describes. diff --git a/site/content/docs/(latest)/errors/catching.mdx b/site/content/docs/(latest)/errors/catching.mdx index 19b2742..471b175 100644 --- a/site/content/docs/(latest)/errors/catching.mdx +++ b/site/content/docs/(latest)/errors/catching.mdx @@ -2,3 +2,97 @@ title: Catch errors description: Handle an error by its tag, or one status. --- + +This page shows how to handle a call's errors: by their tag, or by the +response's status. For the errors themselves, see +[Call errors](/docs/errors). + +## Catch errors by tag + +To handle a call's errors, catch them by tag with `Effect.catchTags`: + +```ts +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import type { Fetch } from "@monarcode/effetch"; + +declare const api: Fetch.Client; + +const Todo = Schema.Struct({ id: Schema.Finite, title: Schema.String }); +const ApiError = Schema.Struct({ code: Schema.String }); + +export const todo = (id: number) => + api.get("/todos/:id", { params: { id }, output: Todo, error: ApiError }).pipe( + Effect.catchTags({ + HttpError: (error) => + error.status === 404 + ? Effect.succeed(undefined) + : Effect.fail(error.body?.code ?? `HTTP ${error.status}`), + NetworkError: () => Effect.fail("You're offline"), + DecodeError: (error) => Effect.fail(error.message), + }), + ); +``` + +Each handler gets the error with its fields. You don't have to handle them +all: the ones you leave out stay in the type, for code further up to handle. +For a single error, `Effect.catchTag` does the same. + +`Fetch.FetchError` is the union of the three errors, and `Fetch.isFetchError` +tells them apart from other values. + +## Catch a status + +To handle one or more statuses, use `Fetch.catchStatus`. For the common "a +404 means there's nothing there", `Fetch.optional` succeeds with +`Option.none()` on a 404 and `Option.some(value)` otherwise. + +The following example uses both: + +```ts +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import { Fetch } from "@monarcode/effetch"; + +declare const api: Fetch.Client; + +const Todo = Schema.Struct({ id: Schema.Finite, title: Schema.String }); + +// Option: none for a 404. +export const findTodo = (id: number) => + api.get("/todos/:id", { params: { id }, output: Todo }).pipe(Fetch.optional); + +// "signed out" for a 401 or a 403. +export const me = api + .get("/me") + .pipe( + Fetch.catchStatus([401, 403], (error) => + Effect.succeed(`signed out (${error.status})`), + ), + ); +``` + +Keep the following in mind when you catch a status: + +- The handler gets the `HttpError`, with `status` narrowed to the statuses you + gave, and what it returns joins the call's type. +- `HttpError` stays in the error type, since other statuses still fail with + it. +- Both work on endpoint calls too, and `catchStatus` also takes the effect + first: `Fetch.catchStatus(effect, 404, handler)`. +- A status that [`statusErrors`](/docs/errors/status-errors) maps fails with + your error, not an `HttpError`, so `catchStatus` and `optional` never see + it. Catch your error by its tag instead. +- The handler's `error.body` is `unknown`. For the typed body of an `error` + schema, use `Effect.catchTag("HttpError", …)`. + +## What's next + +- [Typed error bodies](/docs/errors/error-bodies): type `error.body` with a + schema. +- [Errors by status](/docs/errors/status-errors): fail with your own error + for a status, and catch it by its tag. +- [Test errors and statuses](/docs/testing/errors): check your handlers against a fake + backend. diff --git a/site/content/docs/(latest)/errors/error-bodies.mdx b/site/content/docs/(latest)/errors/error-bodies.mdx index 019bb5c..7a18c95 100644 --- a/site/content/docs/(latest)/errors/error-bodies.mdx +++ b/site/content/docs/(latest)/errors/error-bodies.mdx @@ -2,3 +2,32 @@ title: Typed error bodies description: Decode the API's error body with a schema. --- + +APIs usually explain an error in its body, such as +`{ "code": "not_found" }`. This page shows how to give Effetch a schema for +that body, so that `HttpError.body` is decoded and typed. + +## Give a schema for the error body + +You can set the schema in two places: + +- `defaultError`, on the client, applies to every call; +- `error`, on a call or an [endpoint](/docs/endpoints), replaces it. + +## Read the body + +`body` is the decoded body, or `undefined` if it didn't match the schema. +Without a schema, it's the parsed JSON. Reading it never fails the call, and +the raw body is always on `text`. + +`Fetch.HttpError.With` is the type of an `HttpError` whose `body` is `B`, +for your own function signatures. + +## What's next + +- [Catch errors](/docs/errors/catching): read the typed body in an + `HttpError` handler. +- [Errors by status](/docs/errors/status-errors): turn a status and its body + into your own error. +- [Client configuration](/docs/clients/configuration): set `defaultError` with the + client's other options. diff --git a/site/content/docs/(latest)/errors/index.mdx b/site/content/docs/(latest)/errors/index.mdx index 3364dcf..4956e3b 100644 --- a/site/content/docs/(latest)/errors/index.mdx +++ b/site/content/docs/(latest)/errors/index.mdx @@ -2,3 +2,38 @@ title: Call errors description: Learn what a call can fail with and how each error is typed. --- + +Every call's type lists the ways it can fail, so TypeScript knows which +errors you've handled and which are left. This page describes those errors. +The other pages in this section show how to catch them and how to turn the +API's error responses into errors of your own. + +## What can go wrong + +A call can fail in three ways, each with its own tagged error. Plugins can add +their own, such as `timeout`'s `TimeoutError`, and +[`statusErrors`](/docs/errors/status-errors) can turn an `HttpError` into one +of your own. + +The following table lists each error, when it happens and the fields it +carries: + +| Error | When | Fields | +| ----------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------- | +| `NetworkError` | No response: offline, DNS failure, connection refused, CORS rejection. | `method`, `url`, `cause` | +| `HttpError` | A response outside 200–299 (3xx included). | `method`, `url`, `status`, `headers`, `text`, `body` | +| `DecodeError` | A 2xx body that isn't JSON or doesn't match `output`. Only on calls with `output`. | `method`, `url`, `status`, `issue`, `message` | +| `TimeoutError` (plugin) | The `timeout` plugin's limit passed before the response arrived. | `method`, `url`, `duration` | + +## Error pages + +The rest of this section covers each part of handling errors: + +- [Catch errors](/docs/errors/catching): handle an error by its tag, or one + status. +- [Typed error bodies](/docs/errors/error-bodies): decode the API's error + body with a schema. +- [Errors by status](/docs/errors/status-errors): turn an error status into + your own domain error. +- [Logging and defects](/docs/errors/logging-and-defects): what errors keep + out of logs, and which mistakes are defects rather than errors. diff --git a/site/content/docs/(latest)/errors/logging-and-defects.mdx b/site/content/docs/(latest)/errors/logging-and-defects.mdx index 91580ae..772e0f1 100644 --- a/site/content/docs/(latest)/errors/logging-and-defects.mdx +++ b/site/content/docs/(latest)/errors/logging-and-defects.mdx @@ -2,3 +2,32 @@ title: Logging and defects description: Learn which errors are safe to log, and why bugs are defects rather than errors. --- + +This page explains what Effetch keeps out of its errors so you can log them, +and which mistakes make a call die as a defect instead of failing with a +typed error. + +## Errors that are safe to log + +Errors are made to be logged and reported: + +- `url` never includes the query string, so tokens in queries stay out of + logs. +- `HttpError.headers` are Effect `Headers`: `authorization`, `set-cookie` and + other sensitive headers print as ``. + +## Bugs as defects + +Some mistakes are bugs in the calling code, not failures to recover from at +runtime. Those make the Effect die, as a defect, rather than fail with a typed +error: + +- a missing path parameter; +- a body that can't be encoded; +- a query that doesn't match an endpoint's `query` schema; +- a body on a `GET` or `HEAD` request; +- a `baseUrl` with a query string; +- two plugins with the same name; +- a relative URL without a `baseUrl`, outside browsers. + +For the errors a call can fail with, see [Call errors](/docs/errors). diff --git a/site/content/docs/(latest)/errors/status-errors.mdx b/site/content/docs/(latest)/errors/status-errors.mdx index 711c98f..49ee839 100644 --- a/site/content/docs/(latest)/errors/status-errors.mdx +++ b/site/content/docs/(latest)/errors/status-errors.mdx @@ -2,3 +2,164 @@ title: Errors by status description: Turn an error status into your own domain error. --- + +Often a status, or a status with a given body, means a specific error in +your app: a 404 from `GET /todos/:id` is "todo not found", a 400 with +`"code": "INVALID_ROLE"` is "invalid role", a 401 from anywhere is "session +expired". `statusErrors` maps statuses to your own error schemas, and the +call fails with your error instead of an `HttpError`. This page shows how to +set up those maps and how Effetch picks the error for a response. + +## Choose where a map applies + +You can give a map in three places, and they add up: + +- on the client, for every call, such as a `401` from anywhere; +- on an [endpoint](/docs/endpoints), for every call to it, which is where most + of them live; +- on a single call. + +## Map statuses to your errors + +The following program gives a map in all three places, then catches the +errors by their tags: + +```ts +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import { Fetch } from "@monarcode/effetch"; + +class TodoNotFound extends Schema.TaggedError()("TodoNotFound", { + message: Schema.String, +}) {} + +class InvalidRole extends Schema.TaggedError()("InvalidRole", { + code: Schema.Literal("INVALID_ROLE"), + message: Schema.String, +}) {} + +class RoleTaken extends Schema.TaggedError()("RoleTaken", { + code: Schema.Literal("ROLE_TAKEN"), + message: Schema.String, +}) {} + +class SessionExpired extends Schema.TaggedError()( + "SessionExpired", + { message: Schema.String }, +) {} + +const ApiError = Schema.Struct({ code: Schema.String }); +const Todo = Schema.Struct({ id: Schema.Finite, title: Schema.String }); +const User = Schema.Struct({ id: Schema.Finite, role: Schema.String }); + +// For every call +export class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.example.com", + defaultError: ApiError, + statusErrors: { 401: SessionExpired }, +}) {} + +// For every call to an endpoint (see Endpoints) +export const getTodo = Fetch.endpoint("GET /todos/:id", { + output: Todo, + statusErrors: { 404: TodoNotFound }, +}); + +export const program = Effect.gen(function* () { + const api = yield* Api; + const todo = yield* api + .bind(getTodo)({ params: { id: 1 } }) + .pipe(Effect.catchTag("TodoNotFound", () => Effect.succeed(undefined))); + + // For one call + const user = yield* api + .post("/users/:id/roles", { + params: { id: 1 }, + input: Schema.Struct({ role: Schema.String }), + body: { role: "owner" }, + output: User, + statusErrors: { 400: [InvalidRole, RoleTaken] }, // tried in order + }) + .pipe( + Effect.catchTags({ + InvalidRole: (error) => Effect.fail(error.message), + RoleTaken: (error) => Effect.fail(error.message), + }), + ); + return { todo, user }; +}); +``` + +Before the `catchTags`, the role call fails with +`InvalidRole | RoleTaken | SessionExpired | HttpError.With<{ readonly code: string }> | NetworkError | DecodeError`. +`HttpError` stays: a response can always fail to match. + +## How a response is resolved + +Effetch resolves a non-2xx response in the following order: + +1. If the body is empty or isn't JSON, it's an `HttpError`. +2. Otherwise the schemas listed for its status are tried in order: the + call's, then the endpoint's, then the client's. The first one that + decodes the body is the error. +3. If none does, it's the `HttpError` you'd get without `statusErrors`, its + `body` decoded with `error` or `defaultError`. + +With the maps from the program in +[Map statuses to your errors](#map-statuses-to-your-errors), responses fail +as follows: + +| Response | Fails with | +| ------------------------------------------------ | ---------------------------- | +| 400 `{ "code": "INVALID_ROLE", "message": "…" }` | `InvalidRole` | +| 400 `{ "code": "ROLE_TAKEN", "message": "…" }` | `RoleTaken` | +| 400 `{ "code": "MISSING_FIELD" }` | `HttpError` with `body.code` | +| 400 with an empty or non-JSON body | `HttpError` | +| 401 from any endpoint | `SessionExpired` | +| 500 | `HttpError` | + + + + +- **The `_tag`.** Backends don't send one, so when a schema has a literal + `_tag`, as `Schema.TaggedError` classes do, Effetch adds it to the body + before decoding. A body that has its own `_tag` is decoded as it is. +- **Renamed fields.** To read `error_code` into `code`, use + `Schema.encodeKeys`: + `InvalidRole.pipe(Schema.encodeKeys({ code: "error_code" }))`. +- **Lists, not unions.** A `Schema.Union` is decoded as it is, without a + `_tag`: list its members instead. +- **2xx entries never apply**, since a 2xx is decoded with `output`. +- Plugins see the response before any of this, so `retry` still retries by + status. `onError` receives your error, and `api.httpClient` stays raw. +- Maps are copied when they're given, so changing one afterwards changes + nothing. `api.statusErrors` and a `Fetch.endpoint` definition's + `statusErrors` are those copies, frozen; an endpoint's `statusErrors` + joins its own with the client's, each status listing its schemas in the + order they're tried. +- `Fetch.StatusError` is the union of the errors in a map `M`, and + `Fetch.StatusErrorSchema` the union of its schemas, for your own + function signatures. +- A client's type includes its map: `Fetch.Client`. A client + with a map can't be passed where a plain `Fetch.Client` is expected, + since that would hide its errors. + + + + +## See it in a full program + +[`examples/status-errors.ts`](https://github.com/monarcode/effetch/blob/main/examples/status-errors.ts) +puts all of this in one program, and +[`examples/app`](https://github.com/monarcode/effetch/tree/main/examples/app) +uses it across modules. + +## What's next + +- [Catch errors](/docs/errors/catching): catch your errors, and the statuses + you didn't map. +- [Define endpoints](/docs/endpoints/defining): put each endpoint's + `statusErrors` on its definition. +- [Test errors and statuses](/docs/testing/errors): make a fake backend answer with an + error status. diff --git a/site/content/docs/(latest)/examples.mdx b/site/content/docs/(latest)/examples.mdx index 7473c05..07f35cc 100644 --- a/site/content/docs/(latest)/examples.mdx +++ b/site/content/docs/(latest)/examples.mdx @@ -2,3 +2,36 @@ title: Examples description: Find a complete program that uses Effetch, typechecked with the package. --- + +The repository's +[`examples/`](https://github.com/monarcode/effetch/tree/main/examples) folder +has complete programs, typechecked with the package so they always match the +current API. Use them to see a whole feature in context. + +The folder has these programs: + +- [`basic.ts`](https://github.com/monarcode/effetch/blob/main/examples/basic.ts): + a client in a service, the methods, and handling each error. +- [`builtins.ts`](https://github.com/monarcode/effetch/blob/main/examples/builtins.ts): + the built-in plugins, and changing them for one call. +- [`plugins.ts`](https://github.com/monarcode/effetch/blob/main/examples/plugins.ts): + writing plugins, from auth with a service to a `wrap` with its own error. +- [`endpoints.ts`](https://github.com/monarcode/effetch/blob/main/examples/endpoints.ts): + the same app as `builtins.ts`, with endpoints. +- [`backends.ts`](https://github.com/monarcode/effetch/blob/main/examples/backends.ts): + two backends in one file, with shared plugins. +- [`status-errors.ts`](https://github.com/monarcode/effetch/blob/main/examples/status-errors.ts): + your own errors by status, for every call, per endpoint and for one call. +- [`streams.ts`](https://github.com/monarcode/effetch/blob/main/examples/streams.ts): + Server-Sent Events, newline-delimited JSON, and a list paged through by its + `Link` header. +- [`testing.ts`](https://github.com/monarcode/effetch/blob/main/examples/testing.ts): + tests for the `app/` todos module, against a fake backend made from its + endpoints. +- [`app/`](https://github.com/monarcode/effetch/tree/main/examples/app): a + feature-sliced app, with clients as shared infrastructure and each module + defining its own endpoints. + +The examples' +[README](https://github.com/monarcode/effetch/blob/main/examples/README.md) +walks through each one. diff --git a/site/content/docs/(latest)/getting-started.mdx b/site/content/docs/(latest)/getting-started.mdx index c2b0ff5..e198a13 100644 --- a/site/content/docs/(latest)/getting-started.mdx +++ b/site/content/docs/(latest)/getting-started.mdx @@ -2,3 +2,123 @@ title: Getting started description: Declare a client, make a typed call and run it, from an empty file to a working program. --- + +In this tutorial, you write a complete program that fetches a todo from an +API, typed and checked by a schema. Along the way, you meet the four ideas +the rest of Effetch builds on. + +## Before you begin + +Install Effetch and Effect, and check that your project meets the +requirements. For the commands, see [Installation](/docs/installation). + +## Write your first client + +The following program fetches a todo from +[JSONPlaceholder](https://jsonplaceholder.typicode.com), a free fake API. +It's complete, so you can run it as it is: + +```ts +import * as Effect from "effect/Effect"; +import * as FetchHttpClient from "effect/http/FetchHttpClient"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; + +import { Fetch } from "@monarcode/effetch"; + +// 1. What a todo looks like +const Todo = Schema.Struct({ + id: Schema.Finite, + title: Schema.String, + completed: Schema.Boolean, +}); + +// 2. The client, declared once for the whole app +class Api extends Fetch.Service()("Api", { + baseUrl: "https://jsonplaceholder.typicode.com", +}) {} + +// 3. A call +const program = Effect.gen(function* () { + const api = yield* Api; + const todo = yield* api.get("/todos/:id", { + params: { id: 1 }, + output: Todo, + }); + console.log(todo.title); +}); + +// 4. Run it, with the client and the HttpClient that sends the requests +const ApiLive = Api.layer.pipe(Layer.provide(FetchHttpClient.layer)); + +await Effect.runPromise(program.pipe(Effect.provide(ApiLive))); +``` + +## What each part does + +The numbered comments in the program mark its four parts: + +1. **`Todo` describes the response.** Effetch decodes the body with it, so + `todo` is typed, and checked when it arrives. If the API sends something + else, the call fails with a `DecodeError` instead of handing you bad data. +2. **`Api` is your client.** `Fetch.Service` declares it as an Effect + service, with everything its calls have in common: here the base URL, + later the headers, error schemas and plugins. +3. **`api.get` makes the call.** `yield* Api` gives you the client, and the + `:id` in the path is filled in from `params`. +4. **`Api.layer` builds the client.** It needs an `HttpClient` to send the + requests. `FetchHttpClient.layer` uses the global `fetch`. Node's works + too, and in tests you'd use a fake one (see + [Test with a fake backend](/docs/testing)). + + + Calling an API from a web page on another origin? Read the browser notes in + [Platform notes](/docs/platforms) first. + + +## How the pieces fit + +Everything in Effetch builds on four ideas, from the bottom up: + +- **An `HttpClient`** sends requests. It's Effect's, and you choose it when + you run your program: the global `fetch`, Node's, or a fake in tests. +- **A client** is one backend: its base URL, default headers, error schemas + and plugins. You declare it once, with `Fetch.Service`. +- **A call** is one request: a method such as `api.get`, or an + [endpoint](/docs/endpoints) you saved. It returns an Effect, typed by your + schemas, that fails with typed errors. +- **Plugins** wrap every call a client makes, for auth, retries, timeouts + and logging. + +The sidebar follows the same order: +[clients](/docs/clients), [calls](/docs/calls) and +[errors](/docs/errors), then [plugins](/docs/plugins), including +[your own](/docs/plugins/writing), and [endpoints](/docs/endpoints). After +those come [streams](/docs/streaming), [pagination](/docs/pagination), +[how to structure an app](/docs/structuring-an-app) and +[testing](/docs/testing). + +## The examples in these docs + +To stay short, many examples start from `declare const api: Fetch.Client`: a +client without plugins, like the one `yield* Api` gives you when `Api` has +none. In your app, get the client with `yield* Api`. To type a client in a +function signature, use `Effect.Success`, which includes your +plugins and error schemas. + +Some examples also bind an endpoint inline, with `api.bind`, to stay short. +In your app, bind endpoints once, with `Fetch.Endpoints` (see +[Share endpoints as a service](/docs/endpoints/services)). + +Every TypeScript example in these docs is compiled with the package, so +they all match the API. + +## What's next + +- [Declare a client](/docs/clients): see what the client class gives you + and how to type it. +- [Client configuration](/docs/clients/configuration): add headers, error + schemas and plugins to your client. +- [Methods](/docs/calls): make calls with each HTTP method. +- [Call errors](/docs/errors): see what can go wrong in a call and how to + catch it. diff --git a/site/content/docs/(latest)/index.mdx b/site/content/docs/(latest)/index.mdx index 2cf601e..454d58d 100644 --- a/site/content/docs/(latest)/index.mdx +++ b/site/content/docs/(latest)/index.mdx @@ -114,11 +114,10 @@ also: own when you need it. If you know axios or ky, see -[Coming from axios or ky](https://github.com/monarcode/effetch#coming-from-axios-or-ky) +[Coming from axios or ky](/docs/coming-from-axios-or-ky) for how what you know maps to Effetch. ## What's next - [Install Effetch](/docs/installation). -- Read the [full guide](https://github.com/monarcode/effetch#getting-started) - in the README, from your first client to testing. +- Make your first typed call in [Getting started](/docs/getting-started). diff --git a/site/content/docs/(latest)/installation.mdx b/site/content/docs/(latest)/installation.mdx index d01fa18..0289278 100644 --- a/site/content/docs/(latest)/installation.mdx +++ b/site/content/docs/(latest)/installation.mdx @@ -55,11 +55,9 @@ TypeScript uses them to name Effetch's types in the `.d.ts` files it emits for your code. In your own code, import from the main entry. If you're upgrading a project from 0.1.0-rc.3, see -[Upgrading from 0.1.0-rc.3](https://github.com/monarcode/effetch#upgrading-from-010-rc3) +[Upgrade from 0.1.0-rc.3](/docs/upgrading) to move its imports to `Fetch`. ## What's next -- Make your first call: see - [Your first client](https://github.com/monarcode/effetch#your-first-client) - in the README. +- Make your first call: see [Getting started](/docs/getting-started). diff --git a/site/content/docs/(latest)/pagination.mdx b/site/content/docs/(latest)/pagination.mdx index 3057c38..d541616 100644 --- a/site/content/docs/(latest)/pagination.mdx +++ b/site/content/docs/(latest)/pagination.mdx @@ -2,3 +2,112 @@ title: Pagination description: Page through a list with Fetch.paginate, with the cursor in the body or in a header. --- + +Lists are often split into pages: you ask for the first, and the response +says how to get the next. `Fetch.paginate` follows those pages for you, as a +`Stream` of pages. This page shows how to page through a list, with the next +page's state in the body or in a header. + +## Page through a list + +`Fetch.paginate` calls a bound endpoint for the first page, then for the +next one, until `next` says there's none: + +```ts +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; + +import { Fetch } from "@monarcode/effetch"; + +const Todo = Schema.Struct({ id: Schema.Finite, title: Schema.String }); + +const listTodos = Fetch.endpoint("GET /todos", { + query: Schema.Struct({ page: Schema.Finite }), + output: Schema.Array(Todo), +}); + +class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.example.com", +}) {} + +class TodoApi extends Fetch.Endpoints()("TodoApi", Api, { + list: listTodos, +}) {} + +export const allTodos = Effect.gen(function* () { + const todos = yield* TodoApi; + return yield* Fetch.paginate(todos.list, { + start: 1, + request: (page) => ({ query: { page } }), + next: (page, number) => + page.length === 0 ? Option.none() : Option.some(number + 1), + }).pipe(Stream.flattenIterable, Stream.runCollect); +}); +``` + +`Fetch.paginate` takes three options: + +- `start` is the state of the first page, such as a page number or a + cursor. +- `request(state)` gives the page's call options: `params`, `query`, `body` + and `headers`, typed by the endpoint. +- `next(page, state, response)` gives the next page's state, or + `Option.none()` after the last page. + +Each page is one value of the stream, so a page that's a list stays a list. +`Stream.flattenIterable` gives its items one by one. + +## How pages are fetched + +The stream is lazy: it sends a page's call only when the page is needed, so +`Stream.take(1)` sends one. A call that fails fails the stream with the +call's error. + +`Fetch.paginate` takes a bound endpoint, from `Fetch.Endpoints`, +`client.bind`, `client.bindAll` or `client.endpoint`. A definition made by +`Fetch.endpoint` needs binding first, and a stream endpoint can't be paged. + +## Read the cursor from a header + +When the next page's cursor is in a header, such as a `Link` header, define +the endpoint with `responseMode: "decoded-and-response"`. `next` then gets +each page's response: + +```ts +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; + +import { Fetch } from "@monarcode/effetch"; + +declare const api: Fetch.Client; + +const Item = Schema.Struct({ id: Schema.Finite }); + +const listItems = Fetch.endpoint("GET /items", { + output: Schema.Array(Item), + responseMode: "decoded-and-response", +}); + +// The cursor is percent-encoded in the URL, and `query` encodes it again. +const nextCursor = (link: string | undefined) => + Option.fromNullishOr( + /[?&]cursor=([^&>]+)[^>]*>;\s*rel="next"/.exec(link ?? "")?.[1], + ).pipe(Option.flatMap(Option.liftThrowable(decodeURIComponent))); + +export const allItems = Fetch.paginate(api.bind(listItems), { + start: undefined as string | undefined, + request: (cursor) => (cursor === undefined ? {} : { query: { cursor } }), + next: (_items, _cursor, response) => nextCursor(response.headers.link), +}); +``` + +## What's next + +- [Call an endpoint](/docs/endpoints/calling): bind an endpoint so + `Fetch.paginate` can call it. +- [Typed query parameters](/docs/endpoints/typed-query): type the page or + cursor that `request` sends. +- [Streaming responses](/docs/streaming): read a body that arrives a piece at + a time. diff --git a/site/content/docs/(latest)/platforms.mdx b/site/content/docs/(latest)/platforms.mdx index 56b01f3..5a662de 100644 --- a/site/content/docs/(latest)/platforms.mdx +++ b/site/content/docs/(latest)/platforms.mdx @@ -2,3 +2,62 @@ title: Platform notes description: Set up Effetch for browsers and React Native. --- + +This page covers what to know, and what to set up, when you run Effetch in a +browser or in React Native. + +Effetch has no platform-specific imports or builds, and runs wherever Effect's +`HttpClient` does: browsers, React Native, Node 20 or newer, Bun and Deno. +Two platforms need a little setup. + +## Browsers + +Effect's `HttpClient` adds `traceparent` and `b3` tracing headers to every +request. Cross-origin calls to APIs that don't allow those headers then fail +the CORS preflight. Turn propagation off in the layer that makes the client, +and it applies to all its calls: + +```ts +import * as FetchHttpClient from "effect/http/FetchHttpClient"; +import * as HttpClient from "effect/http/HttpClient"; +import * as Layer from "effect/Layer"; + +import { Fetch } from "@monarcode/effetch"; + +export class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.example.com", +}) {} + +export const ApiLive = Api.layer.pipe( + Layer.provide(Layer.succeed(HttpClient.TracerPropagationEnabled)(false)), + Layer.provide(FetchHttpClient.layer), +); +``` + +In a browser, a relative path without a `baseUrl` is resolved against the +page's URL. + +## React Native + +React Native differs from the other platforms in these ways: + +- Effetch doesn't use `URL` itself. Effect's `HttpClient` does, including + `searchParams`. Expo provides a standard `URL`. In a React Native app + without Expo, install a polyfill such as `react-native-url-polyfill`. +- Effetch and Effect use package `exports` (`effect/http/HttpClient`, + `@monarcode/effetch/plugins`). Metro resolves them by default from React + Native 0.79 (Expo SDK 53). On older versions, set + `resolver.unstable_enablePackageExports = true` in `metro.config.js`. +- `FetchHttpClient.layer` uses the global `fetch`. +- React Native's `fetch` doesn't stream response bodies, so `api.sse`, + `api.ndjson` and stream endpoints fail with a `DecodeError` there. In + Expo, provide the `fetch` from `expo/fetch`, which streams, as + `FetchHttpClient.Fetch`: + `Layer.succeed(FetchHttpClient.Fetch)(expoFetch as typeof globalThis.fetch)`. +- To upload a file a picker gave you, send its `{ uri, name, type }` in a + `Fetch.UploadFile` field (see [Upload files](/docs/calls/uploads)). + React Native's `FormData` reads the file from disk by `uri`, and can't send + a `Blob`. +- Metro's terminal drops `console.groupCollapsed` and everything inside it, + so `consoleLogger` doesn't collapse its groups in React Native (see the + details in [Log to the console](/docs/plugins/console-logging)). diff --git a/site/content/docs/(latest)/plugins/console-logging.mdx b/site/content/docs/(latest)/plugins/console-logging.mdx index d2b7d5a..0b162aa 100644 --- a/site/content/docs/(latest)/plugins/console-logging.mdx +++ b/site/content/docs/(latest)/plugins/console-logging.mdx @@ -1,4 +1,161 @@ --- title: Log to the console -description: Log calls to the console during development. +description: Print every call's route, status, headers, bodies and error to the console during development. --- + +`logger` writes one structured entry per call for production logs, and leaves +headers, query strings and bodies out. `consoleLogger` is for development: it +prints everything about a call to the console, as a group devtools can +expand. This page shows how to add it, what it prints, and how to tune it. + +## Add the console logger + +Add `consoleLogger` to the client's plugins. This example turns it on only in +development, flags calls slower than a second, and redacts an extra body key: + +```ts +import { Fetch } from "@monarcode/effetch"; +import { consoleLogger } from "@monarcode/effetch/plugins"; + +declare const isDevelopment: boolean; + +export class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.example.com", + plugins: [ + consoleLogger({ + enabled: isDevelopment, + slow: "1 second", + redact: { body: ["otp"] }, + }), + ], +}) {} +``` + +## Read the output + +Each call prints a line, which opens a group with the details: + +```text +▸ GET /todos/:id 200 OK 35 ms 1.2 kB +▸ ✗ GET /todos 3.0 s → NetworkError: Failed to fetch +▸ ⚠ GET /reports/:id 200 OK 2.4 s (slow) +▾ ✗ POST /users/:id/roles 400 Bad Request 120 ms → InvalidRole: No such role + POST https://api.example.com/users/7/roles + request headers { accept: "application/json", authorization: "" } + request body { role: "owner" } + response headers { "content-type": "application/json" } + response body { code: "INVALID_ROLE", message: "No such role" } + error InvalidRole { code: "INVALID_ROLE", message: "No such role" } +``` + +It prints each call once it's over, with the error it ended with, after +[`statusErrors`](/docs/errors/status-errors) and decoding. Values are printed +as objects, so devtools can expand them. + +## Options + +`consoleLogger` takes the following options: + +| Option | Default | What it does | +| --------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `enabled` | `true` | `false` prints nothing, and keeps the plugin's type, so it can stay in the list in production. | +| `detail` | `"full"` | `"summary"` prints the line alone; `"headers"` adds the URL, headers and error; `"full"` adds the bodies. | +| `only` | `"all"` | `"errors"` prints failed calls only. | +| `collapsed` | `true` | Whether groups start collapsed. `false` by default in React Native, where Metro's terminal drops collapsed groups. Node, Bun and Deno print them expanded. | +| `slow` | `false` | A duration, such as `"1 second"`: slower calls are flagged. | +| `maxBodyLength` | `10_000` | Body text longer than this is cut. JSON within it is printed as an object. | +| `redact` | | `{ headers, query, body }`: more names to redact, as strings (ignoring case, `-` and `_`) or regular expressions. `false` redacts nothing. | +| `filter` | | `(call) => boolean`: prints only the calls it accepts. `call` has the `route`, the `request`, the `response`, the `exit` and the `durationMs`. | +| `color` | `"auto"` | `"css"` (browser devtools), `"ansi"` (terminals), or `false`. `"auto"` uses `"css"` where there's a `document`, else plain text. | + +## Change the output for one call + +Calls can change `detail`, `only`, `collapsed`, `slow` and `maxBodyLength`, or +skip it with `false`: + +```ts +import * as Effect from "effect/Effect"; + +import { Fetch } from "@monarcode/effetch"; +import { consoleLogger } from "@monarcode/effetch/plugins"; + +class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.example.com", + plugins: [consoleLogger()], +}) {} + +export const program = Effect.gen(function* () { + const api = yield* Api; + yield* api.get("/reports/export", { + plugins: { consoleLogger: { detail: "summary" } }, + }); + yield* api.get("/health", { plugins: { consoleLogger: false } }); +}); +``` + +## Redaction, bodies, platforms and timing + +Expand the following sections for what `consoleLogger` redacts, which bodies +it reads, how it behaves on each platform, and when it runs: + + + + +It replaces these with ``, matching names ignoring case, `-` and +`_`: + +- headers in Effect's `Headers.CurrentRedactedNames` (`authorization`, + `cookie`, `set-cookie`, `x-api-key`), `proxy-authorization`, + `x-auth-token`, `x-access-token`, `x-refresh-token`, `x-session-token`, + `x-csrf-token`, `x-xsrf-token`, `x-client-secret` and + `x-amz-security-token`; +- keys in JSON and form bodies, at any depth: `token`, `accessToken`, + `refreshToken`, `idToken`, `authToken`, `apiToken`, `sessionToken`, + `csrfToken`, `xsrfToken`, `secret`, `clientSecret`, `apiSecret`, + `apiKey`, `privateKey`, and any name containing `password`; +- query parameters with the same names, `key`, `sig`, `signature` and the + signed-URL ones (`X-Amz-Signature`, `X-Goog-Signature`, …), values passed + as `Redacted`, and credentials in the URL (`https://user:password@…`). + +They're exact names rather than patterns, so fields such as `total_tokens` +stay visible. Plain-text bodies are printed as they are. A call's error is +printed as a copy of its fields, redacted like a body, without an +`HttpError`'s `text` or a `DecodeError`'s `issue`, which the response body +line shows. Defects are printed as they are. + + + + +- It only reads a response body that's text: JSON, `text/*` other than event + streams, XML or a form, up to 1 MB. Effetch has read it already to check + the status or decode it, and Effect caches it. A call without `output` + returns the response itself, so its body isn't read, and stays yours to + stream. Neither is an interrupted call's. +- It writes through Effect's `Console`, so you can provide another one, with + `console.log` and groups only. React Native turns `console.error` into an + error screen. +- In React Native, groups start expanded: Metro's terminal silently drops + `console.groupCollapsed` and everything logged inside it. React Native is + detected by `navigator.product`, which it sets to `"ReactNative"`. +- It runs when the call is over, so where it sits in the plugin list doesn't + matter: a retried call is one entry, and its duration covers every + attempt. The size comes from `content-length`, or from the body when it's + read. +- When a plugin fails on a response, such as an auth plugin on a 401, that + response is shown with the plugin's error. +- `slow` that isn't a duration throws when the plugin is made. +- The request shown is the one that was sent, after plugins such as `bearer` + changed it. When no response came back, it's the one the call built, + before plugins ran. + + + + +## What's next + +- [Built-in plugins](/docs/plugins): compare `consoleLogger` with `logger` + for production logs. +- [Change plugins for one call](/docs/plugins/per-call): skip or adjust any + plugin on a single call. +- [Write a plugin](/docs/plugins/writing): build your own logging or metrics + on the `onExit` hook that `consoleLogger` uses. diff --git a/site/content/docs/(latest)/plugins/index.mdx b/site/content/docs/(latest)/plugins/index.mdx index 6d523d9..1c1f5e2 100644 --- a/site/content/docs/(latest)/plugins/index.mdx +++ b/site/content/docs/(latest)/plugins/index.mdx @@ -1,4 +1,84 @@ --- title: Built-in plugins -description: Add a bearer token, retries, a timeout and logging to a client. +description: Add a bearer token, retries, a timeout and logging to every call a client makes. --- + +Most APIs need the same things on every call: a token, retries when the +network drops, a time limit, a log line. Plugins add that behavior to every +call a client makes. You list them in the client's config, and any call can +turn one off or adjust it. This page shows the plugins that ship with Effetch +and what each one does. + +## Add plugins to a client + +The built-in plugins come from `@monarcode/effetch/plugins`. List them in the +client's `plugins` option: + +```ts +import * as Effect from "effect/Effect"; + +import { Fetch } from "@monarcode/effetch"; +import { bearer, logger, retry, timeout } from "@monarcode/effetch/plugins"; + +declare const readToken: () => Promise; + +export class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.example.com", + plugins: [ + logger({ level: "Info" }), + retry({ times: 2 }), + timeout({ duration: "10 seconds" }), + bearer({ token: () => readToken() }), + ], +}) {} + +export const withEffectToken = bearer({ token: Effect.succeed("token") }); +``` + +The order in this example is the one to use. To learn why, see +[Plugin order](/docs/plugins/order). + +## What each plugin does + +The following table lists each built-in plugin, what it does, and what a call +can pass for it in its `plugins` option: + +| Plugin | What it does | Per call | +| ------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------- | +| `bearer({ token, scheme?, refresh? })` | Sends `Authorization: Bearer `. The token is a string, a function of the request (sync or async), or an Effect, read for every request. `null`, `undefined` and `""` send no header, and an existing `Authorization` header is kept. With `refresh`, a `401` gets a new token and the request is sent again, once. See [Refresh a token](/docs/plugins/token-refresh). | `false` | +| `logger({ level? })` | Logs one entry per call at Debug (or Info): `GET 200 (35ms)`, or `failed` with the cause, with the call's [route](/docs/plugins/writing#read-the-route) as an annotation. Never logs headers or query strings. | `false` | +| `consoleLogger(options?)` | Prints each call to the console while you develop: a line with the route, status, duration and outcome, opening a group with the full URL, headers, bodies and error. Sensitive headers, query parameters and body keys are redacted. See [Log to the console](/docs/plugins/console-logging). | `false`, its settings | +| `retry({ times?, schedule?, methods?, statuses?, retryAfter?, budget? })` | Retries network errors and 408, 429, 500, 502, 503 and 504, 2 times by default, with jittered exponential backoff from 200ms. Only idempotent methods (`GET`, `HEAD`, `OPTIONS`, `PUT`, `DELETE`) by default, so a `POST` is never sent twice. When retries run out, the last response is returned. `retryAfter` waits as `Retry-After` asks, and `budget` limits the whole call. See [Retry-After and a time limit](/docs/plugins/retry-after). | `false`, `{ times }`, and `{ budget }` with a budget | +| `timeout({ duration })` | Fails with `TimeoutError` and aborts the request when the response headers don't arrive in time. Downloading the body isn't covered. | `false`, `{ duration }` | + +## Fail with a typed error from a token + +A `bearer` token function that throws, or whose promise rejects, makes the +call die. To fail with a typed error instead, pass an Effect: its error and +services become the client's, and the client's layer (or `Fetch.make`) asks +for the services. + +## Choose a time limit + +Time limits apply per attempt or to the whole call: + +- **Per attempt:** `timeout`, placed after `retry` in the plugin list, as in + the example on this page. Each attempt gets the full duration, and a + timed-out attempt isn't retried. +- **For the whole call:** `retry({ budget })`, every attempt and wait + included. For one call, or on a client without `retry`, wrap the call in + `Effect.timeout`. + +To use both together, see +[Retry-After and a time limit](/docs/plugins/retry-after). + +## What's next + +- [Refresh a token](/docs/plugins/token-refresh): renew an expired token + without failing the call. +- [Retry-After and a time limit](/docs/plugins/retry-after): honor + `Retry-After` and cap the whole call. +- [Change plugins for one call](/docs/plugins/per-call): skip or adjust a + plugin on a single call. +- [Write a plugin](/docs/plugins/writing): add behavior the built-in plugins + don't cover. diff --git a/site/content/docs/(latest)/plugins/order.mdx b/site/content/docs/(latest)/plugins/order.mdx index 0d15fdc..26a05fb 100644 --- a/site/content/docs/(latest)/plugins/order.mdx +++ b/site/content/docs/(latest)/plugins/order.mdx @@ -1,4 +1,30 @@ --- title: Plugin order -description: Learn the order plugins run in. +description: Learn the order plugins run in, and why logger, retry, timeout and bearer go in that order. --- + +The order of a client's `plugins` list decides what each plugin sees. This +page explains how plugins nest, and why the order used in +[Built-in plugins](/docs/plugins) is the one to use. + +## How plugins nest + +The first plugin is the outermost: it runs first on the way out, and last on +the way back. + +## The recommended order + +List the built-in plugins as `logger`, `retry`, `timeout`, `bearer`, as in +the example in [Built-in plugins](/docs/plugins). With that order: + +- `logger` sees the whole call, retries included (`consoleLogger` sees the + whole call wherever it is); +- each retry gets its own timeout, and asks for the token again; +- a timed-out attempt isn't retried; +- `retry`'s `budget` covers every attempt and wait, while `timeout` covers + one attempt; +- a `401` that `bearer` refreshes is sent again inside the same attempt, so + it shares that attempt's timeout. + +For when each hook runs in that order, see the hooks table in +[Write a plugin](/docs/plugins/writing). diff --git a/site/content/docs/(latest)/plugins/per-call.mdx b/site/content/docs/(latest)/plugins/per-call.mdx index 60ad145..f1d4855 100644 --- a/site/content/docs/(latest)/plugins/per-call.mdx +++ b/site/content/docs/(latest)/plugins/per-call.mdx @@ -2,3 +2,55 @@ title: Change plugins for one call description: Turn off or adjust a client's plugin for one call. --- + +A client's plugins run on every call, but some calls need something +different: a login that sends no token, or a slow export that needs more +time. This page shows how to change a client's plugins for one call. + +## Skip or adjust a plugin + +Any call can skip a plugin with `false`, and plugins with options take part of +them. TypeScript checks the plugin names and the option types: + +```ts +import * as Effect from "effect/Effect"; + +import { Fetch } from "@monarcode/effetch"; +import { bearer, retry, timeout } from "@monarcode/effetch/plugins"; + +class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.example.com", + plugins: [ + retry(), + timeout({ duration: "10 seconds" }), + bearer({ token: "token" }), + ], +}) {} + +export const program = Effect.gen(function* () { + const api = yield* Api; + + // Logging in sends no token. + yield* api.post("/auth/login", { + body: { user: "ada" }, + plugins: { bearer: false }, + }); + + // A slow export gets more time, and isn't retried. + yield* api.get("/reports/export", { + plugins: { timeout: { duration: "2 minutes" }, retry: { times: 0 } }, + }); +}); +``` + +To see what each built-in plugin accepts per call, see the **Per call** column +in [Built-in plugins](/docs/plugins). + +## What's next + +- [Write a plugin](/docs/plugins/writing): write your own plugins, with + options that calls can override. +- [Retry-After and a time limit](/docs/plugins/retry-after): override the + whole-call budget for one call. +- [Log to the console](/docs/plugins/console-logging): change the console + output for one call. diff --git a/site/content/docs/(latest)/plugins/recipes.mdx b/site/content/docs/(latest)/plugins/recipes.mdx index 172bb87..495c464 100644 --- a/site/content/docs/(latest)/plugins/recipes.mdx +++ b/site/content/docs/(latest)/plugins/recipes.mdx @@ -2,3 +2,101 @@ title: Plugin recipes description: Copy a plugin that signs out on a 401, or one that sets a deadline with its own error. --- + +These plugins solve common problems, and you can copy them into your app. +Each one shows a different part of the plugin API: hooks that need a service +and add an error, and a `wrap` with an option calls can override. + +## Sign out on a 401 + +The classic plugin: send the session's token, and when the API answers `401`, +sign out and fail with a typed `SessionExpired`. To renew the token instead, +see [Refresh a token](/docs/plugins/token-refresh). + +The plugin reads the token from a `Session` service in `onRequest`, and +signs out in `onResponse`: + +```ts +import * as Context from "effect/Context"; +import * as Data from "effect/Data"; +import * as Effect from "effect/Effect"; +import * as HttpClientRequest from "effect/http/HttpClientRequest"; + +import { Fetch } from "@monarcode/effetch"; + +export class SessionExpired extends Data.TaggedError("SessionExpired")<{}> {} + +export class Session extends Context.Service< + Session, + { + readonly accessToken: Effect.Effect; + readonly signOut: Effect.Effect; + } +>()("Session") {} + +export const auth = Fetch.plugin({ + name: "auth", + onRequest: (request) => + Effect.gen(function* () { + const session = yield* Session; + const token = yield* session.accessToken; + return token === undefined + ? request + : HttpClientRequest.bearerToken(request, token); + }), + onResponse: (response) => + Effect.gen(function* () { + if (response.status !== 401) { + return response; + } + const session = yield* Session; + yield* session.signOut; + return yield* new SessionExpired(); + }), +}); + +// Api.layer now needs Session; calls fail with SessionExpired too. +export class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.example.com", + plugins: [auth], +}) {} +``` + +## Set a deadline with its own error + +A `wrap` that adds its own error, with an option calls can override: + +```ts +import * as Data from "effect/Data"; +import * as Effect from "effect/Effect"; +import * as HttpClient from "effect/http/HttpClient"; + +import { Fetch } from "@monarcode/effetch"; + +export class TooSlow extends Data.TaggedError("TooSlow")<{ + readonly url: string; +}> {} + +export const deadline = Fetch.plugin({ + name: "deadline", + defaults: { millis: 5000 }, + wrap: (client, options) => + HttpClient.transform(client, (response, request) => + Effect.gen(function* () { + const { millis } = yield* options; + return yield* Effect.timeoutOrElse(response, { + duration: millis, + orElse: () => Effect.fail(new TooSlow({ url: request.url })), + }); + }), + ), +}); +``` + +## What's next + +- [Write a plugin](/docs/plugins/writing): learn the hooks these recipes use. +- [Refresh a token](/docs/plugins/token-refresh): renew the token on a `401` + in place of signing out. +- [Catch errors](/docs/errors/catching): handle `SessionExpired` and + `TooSlow` where you make the call. diff --git a/site/content/docs/(latest)/plugins/retry-after.mdx b/site/content/docs/(latest)/plugins/retry-after.mdx index 1758c38..7a7247b 100644 --- a/site/content/docs/(latest)/plugins/retry-after.mdx +++ b/site/content/docs/(latest)/plugins/retry-after.mdx @@ -2,3 +2,49 @@ title: Retry-After and a time limit description: Honor a Retry-After header without going past a deadline. --- + +Overloaded or slow servers can ask you to wait, or take too long to answer. +This page shows how to make `retry` wait as a server asks, and how to limit +the time a whole call may take. + +## Retry options for overloaded or slow servers + +`retry` has two options for servers that are overloaded or slow: + +- `retryAfter`: when a retried response has a `Retry-After` header, wait as + long as it asks (`Retry-After: 120`, or an HTTP date) in place of the + schedule's delay. `true` waits up to 1 minute, and `{ max }` up to `max`. + It's off by default, so a server can't make calls wait. +- `budget`: how long the whole call may take, every attempt and wait + included. No retry is made when its wait would end at or after the budget: + the call ends with its last response or `NetworkError`. When the budget runs + out during an attempt, the attempt is aborted, and the call fails with + `TimeoutError`. Calls can override it. + +## Limit each attempt and the whole call + +For "10 seconds per attempt, 30 seconds in all", use both `timeout` and a +budget: + +```ts +import { Fetch } from "@monarcode/effetch"; +import { retry, timeout } from "@monarcode/effetch/plugins"; + +export class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.example.com", + plugins: [ + retry({ times: 5, retryAfter: true, budget: "30 seconds" }), + timeout({ duration: "10 seconds" }), + ], +}) {} + +// Per call: api.get("/report", { plugins: { retry: { budget: "2 minutes" } } }) +``` + +## What's next + +- [Change plugins for one call](/docs/plugins/per-call): give one call a + longer budget or timeout. +- [Plugin order](/docs/plugins/order): see why `timeout` goes after `retry`. +- [Built-in plugins](/docs/plugins): see every option `retry` and `timeout` + take. diff --git a/site/content/docs/(latest)/plugins/token-refresh.mdx b/site/content/docs/(latest)/plugins/token-refresh.mdx index 94243f7..4fd69e0 100644 --- a/site/content/docs/(latest)/plugins/token-refresh.mdx +++ b/site/content/docs/(latest)/plugins/token-refresh.mdx @@ -1,4 +1,73 @@ --- title: Refresh a token -description: Refresh an expired token and replay the call. +description: Renew an expired access token with the bearer plugin and send the request again. --- + +To renew an expired access token without failing the call, give `bearer` a +`refresh`. This page shows how to set it up and how refreshing behaves. + +## Add a refresh function + +When a request that `bearer` signed gets a `401`, `bearer` asks `refresh` for +a new token, then sends the request again with it. Pass `refresh` next to +`token`: + +```ts +import { Fetch } from "@monarcode/effetch"; +import { bearer } from "@monarcode/effetch/plugins"; + +declare const tokens: { + readonly access: () => string | undefined; + readonly renew: () => Promise; +}; + +export class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.example.com", + plugins: [ + bearer({ token: () => tokens.access(), refresh: () => tokens.renew() }), + ], +}) {} +``` + +The new token is used for that request only. Store it where `token` reads it, +so later requests send it too. To sign out instead, see the +[Sign out on a 401](/docs/plugins/recipes#sign-out-on-a-401) recipe. + +## How refreshing behaves + + + + +- `refresh` is a function of the refused request, as it was sent, sync or + async, or an Effect. Like `token`, an Effect's error and services become + the client's. +- Calls refused with the same token share one refresh, so the token is + renewed once, and they all get its token or its error. Calls refused with + different tokens, such as other users' on a server, get their own. +- A call that times out or is interrupted while it waits doesn't cancel the + refresh for the others. +- The request is sent again once. If the new token is refused too, the call + ends with that `401`. +- When `refresh` gives `null`, `undefined` or `""`, such as when the session + has ended, the call ends with the `401`, and nothing more is sent. +- A request with its own `Authorization` header, sent without a token, or + with a stream body, which can't be sent twice, isn't refreshed. Neither is + a call that skips `bearer`. +- Make the refresh call itself skip `bearer`: `plugins: { bearer: false }`. + Calls made inside an Effect `refresh` never refresh, but a function that + runs the client with `Effect.runPromise` can't be told apart: a `401` to + it would wait for the refresh it's part of. +- Every method is sent again, a `POST` included: a `401` means the server + didn't act on the request. + + + + +## What's next + +- [Plugin recipes](/docs/plugins/recipes): sign out and fail with a typed + error on a `401`, in place of refreshing. +- [Change plugins for one call](/docs/plugins/per-call): make the refresh + call skip `bearer`. +- [Plugin order](/docs/plugins/order): see how a refreshed request shares its + attempt's timeout. diff --git a/site/content/docs/(latest)/plugins/writing.mdx b/site/content/docs/(latest)/plugins/writing.mdx index b5e8e44..fe3fddd 100644 --- a/site/content/docs/(latest)/plugins/writing.mdx +++ b/site/content/docs/(latest)/plugins/writing.mdx @@ -2,3 +2,152 @@ title: Write a plugin description: Build a first plugin, then learn the hooks and how a plugin knows the route. --- + +When the built-in plugins don't cover what you need, write your own. The +built-in ones are written with the same API. In this tutorial, you write a +plugin that pins the API version on every request, then learn the hooks a +plugin can use and how it knows which route a call is for. + +## Write your first plugin + +A plugin is a name and one or more hooks. This one pins the API version on +every request, with an option that a call can change: + +```ts +import * as Effect from "effect/Effect"; +import * as HttpClientRequest from "effect/http/HttpClientRequest"; + +import { Fetch } from "@monarcode/effetch"; + +export const apiVersion = Fetch.plugin({ + name: "apiVersion", + defaults: { version: "2024-06-01" }, + onRequest: (request, ctx) => + Effect.succeed( + HttpClientRequest.setHeader(request, "api-version", ctx.options.version), + ), +}); + +class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.example.com", + plugins: [apiVersion], +}) {} + +export const program = Effect.gen(function* () { + const api = yield* Api; + yield* api.get("/reports", { + plugins: { apiVersion: { version: "2025-01-01" } }, + }); +}); +``` + +`Fetch.plugin` infers the plugin's name, options, errors and services from +what you give it, so calls can override `apiVersion` by name, and their +options are checked. `ctx.options` is the plugin's `defaults` merged with the +call's override, so a plugin needs `defaults` to take options. + +## Hooks + +A plugin can define any of the following hooks: + +| Hook | Runs | +| ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- | +| `onRequest(request, ctx)` | Before the request is sent, in array order. Returns the request to send, or fails. It sees the full URL and the client's headers. | +| `onResponse(response, ctx)` | On every response, non-2xx included, in reverse order. Returns the response, or fails. The status check and decoding come after all plugins. | +| `onError(error, ctx)` | After a call fails or dies, in array order. It can't change the outcome. | +| `onExit(exit, ctx)` | After every call, whatever the outcome, in array order, after `onError`. It can't change the outcome. | +| `wrap(client, options, route)` | Wraps the plugins after it and the network, for retries, timeouts and the like. It can add errors but can't remove them. | + +`ctx.request` is the request: in `onResponse`, the one this plugin passed on; +in `onError` and `onExit`, the one the call built. + +### Record every call with onExit + +`onExit` gets the call's `Exit`: its result (the decoded `output`, or the +response for a call without one), or the cause of its failure, defect or +interruption. Its `ctx` also has: + +- `response`: the one the plugins returned; when a plugin failed after a + response arrived, the last one the network sent; `undefined` when none + arrived; +- `durationMs`: the time from sending the request to decoding the body, + retries included. + +It suits logging and metrics, and is what `consoleLogger` uses. This plugin +records each call's route, outcome and duration: + +```ts +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; + +import { Fetch } from "@monarcode/effetch"; + +declare const record: (route: string, ok: boolean, durationMs: number) => void; + +export const metrics = Fetch.plugin({ + name: "metrics", + onExit: (exit, ctx) => + Effect.sync(() => record(ctx.route, Exit.isSuccess(exit), ctx.durationMs)), +}); +``` + +The call returns once every `onExit` hook is done, so keep them quick, and +fork anything slow. + +## Read the route + +`ctx.route` is the call's method and path as written, before the params are +filled in: `"GET /users/:id"`, whether the call was +`api.get("/users/:id", …)` or an [endpoint](/docs/endpoints). It's the same +for every user ID, so it's what to group logs, metrics and error reports by. +It's `undefined` for requests sent through `client.httpClient`. + +A `wrap` reads it from its third argument, an Effect like `options`. The +following example reads the route in an `onError` hook and in a `wrap`: + +```ts +import * as Effect from "effect/Effect"; +import * as HttpClient from "effect/http/HttpClient"; + +import { Fetch } from "@monarcode/effetch"; + +declare const report: (error: unknown, route: string | undefined) => void; + +export const errorReporter = Fetch.plugin({ + name: "errorReporter", + onError: (error, ctx) => Effect.sync(() => report(error, ctx.route)), +}); + +export const timing = Fetch.plugin({ + name: "timing", + wrap: (client, _options, route) => + HttpClient.transform(client, (response, request) => + Effect.gen(function* () { + const label = (yield* route) ?? request.url; + return yield* Effect.withLogSpan(response, label); + }), + ), +}); +``` + +## Tips + +Keep these rules in mind as you write plugins: + +- Services a plugin needs are required once, by the client's layer (or by + `Fetch.make`). Calls don't need them. Services provided around a call win + over those the client was built with. +- Plugin names must be unique. +- Write `wrap` bodies with `Effect.gen`. A ternary that returns two different + Effects can't be typed. +- Pass plugin lists inline, or let TypeScript infer them. Annotating a list as + `Fetch.Plugin.Any[]` erases the plugins' types. + +## What's next + +- [Plugin recipes](/docs/plugins/recipes): copy a plugin that signs out on a + `401`, or one that sets a deadline with its own error. +- [Plugin order](/docs/plugins/order): decide where your plugin goes in the + list. +- [Change plugins for one call](/docs/plugins/per-call): skip or adjust your + plugin on a single call. diff --git a/site/content/docs/(latest)/reference/compatibility.mdx b/site/content/docs/(latest)/reference/compatibility.mdx deleted file mode 100644 index 4aeb7ad..0000000 --- a/site/content/docs/(latest)/reference/compatibility.mdx +++ /dev/null @@ -1,4 +0,0 @@ ---- -title: Compatibility -description: Check the supported Effect versions and runtimes. ---- diff --git a/site/content/docs/(latest)/reference/fetch-test.mdx b/site/content/docs/(latest)/reference/fetch-test.mdx deleted file mode 100644 index 07f154f..0000000 --- a/site/content/docs/(latest)/reference/fetch-test.mdx +++ /dev/null @@ -1,4 +0,0 @@ ---- -title: FetchTest -description: Look up a member of the FetchTest namespace from @monarcode/effetch/test. ---- diff --git a/site/content/docs/(latest)/reference/fetch.mdx b/site/content/docs/(latest)/reference/fetch.mdx deleted file mode 100644 index 541f45f..0000000 --- a/site/content/docs/(latest)/reference/fetch.mdx +++ /dev/null @@ -1,4 +0,0 @@ ---- -title: Fetch -description: Look up a member of the Fetch namespace. ---- diff --git a/site/content/docs/(latest)/reference/index.mdx b/site/content/docs/(latest)/reference/index.mdx index 9a83f5e..f463a3e 100644 --- a/site/content/docs/(latest)/reference/index.mdx +++ b/site/content/docs/(latest)/reference/index.mdx @@ -1,4 +1,94 @@ --- title: Entry points -description: Find which entry point exports what. +description: Find which entry point exports what, and which page covers each export. --- + +This page lists what each of Effetch's entry points exports, and which page +of these docs covers it. For the known limits, see +[Limitations](/docs/reference/limitations). + +Every export is documented, with an example, in the type declarations your +editor shows. + +## @monarcode/effetch + +`@monarcode/effetch` exports the `Fetch` namespace. + +The exports, and the pages that cover them: + +- `Service`, `ServiceClass` (and `ServiceClass.Any`), `isService`: + [declaring a client](/docs/clients). +- `make`, `ClientConfig`, `Client`: [setting up a client](/docs/clients) + and [making calls](/docs/calls). +- `endpoint`, `UnboundEndpoint`, `UnboundDefinition`, `AnyUnboundEndpoint`: + [defining endpoints](/docs/endpoints/defining). +- `Endpoints`, `EndpointsClass`: + [sharing endpoints as a service](/docs/endpoints/services). +- `BindMethod`, `BindOptions`, `BindAllMethod`, `EndpointDefinitions`, + `EndpointEntry`, `BoundEndpoint`, `BoundEndpoints`: + [other ways to bind endpoints](/docs/endpoints/calling). +- `Endpoint`, `EndpointMethod`, `EndpointDefinition`, `EndpointOptions`, + `EndpointBody`, `EndpointArgs`, `EndpointRoute`, `ValidRoute`, + `RouteMethod`, `RoutePath`: [endpoints](/docs/endpoints). +- `QuerySchema`, `EndpointQuery`: + [typed query parameters](/docs/endpoints/typed-query). +- `EndpointUrlOptions`, `EndpointUrlArgs`: + [building an endpoint's URL](/docs/endpoints/urls). +- `multipart`, `UploadFile`, `UploadFileSchema`, `NativeFile`, + `MultipartSchema`, `MultipartFields`, `MultipartValue`: + [upload files](/docs/calls/uploads). +- `text`, `bytes`, `TextSchema`, `BytesSchema`: + [read text or bytes](/docs/calls/responses#read-text-or-bytes). +- `NetworkError`, `HttpError` (and `HttpError.With`), `DecodeError`, + `FetchError`, `isFetchError`: [errors](/docs/errors). +- `StatusError`, `StatusErrorMap`, `StatusErrorSchema`, + `StatusErrorServices`: [errors by status](/docs/errors/status-errors). +- `catchStatus`, `optional`, `CaughtStatus`: + [catch a status](/docs/errors/catching#catch-a-status). +- `SseEvent`, `StreamElement`, `StreamFormat`, `StreamMethod`, + `StreamOptions`: [streaming responses](/docs/streaming). +- `paginate`, `PaginateOptions`, `PageEndpoint`, `PageRequest`, `PageOf`, + `PageResponse`: [pagination](/docs/pagination). +- `plugin`, `Plugin` (and the `Plugin.*` helper types), `PluginContext`, + `PluginExitContext`: + [writing plugins](/docs/plugins/writing). +- Option and result types, for wrapping the client in your own functions: + `RequestOptions`, `NoBodyRequestOptions`, `BaseOptions`, `BodyOptions`, + `ParamsOption`, `QueryInput`, `QueryOf`, `QueryValue`, `AnySchema`, + `Args`, `Success`, `ResponseMode`, `CallError`, `CallServices`, + `CallEffect`, + `NoBodyMethod`, `BodyMethod`, `RequestMethod`, `PathParamNames`, + `PathParams`, `PathParamValue`. `CallEffect` types a function that + returns a call; to take a call as an argument, accept any + `Effect.Effect`. + +## @monarcode/effetch/plugins + +`@monarcode/effetch/plugins` exports the built-in [plugins](/docs/plugins). + +The exports: + +- `bearer`, `BearerOptions`, `BearerPlugin`, `TokenSource`, `TokenValue`, + `RefreshSource`. +- `logger`, `LoggerOptions`, `LoggerPlugin`. +- `consoleLogger`, `ConsoleLoggerOptions`, `ConsoleLoggerSettings`, + `ConsoleLoggerPlugin`, `ConsoleLoggerDetail`, `ConsoleLoggerRedact`, + `ConsoleLoggerCall`, `ConsoleLoggerColor`. +- `retry`, `RetryOptions`, `RetryPlugin`, `RetryBudgetOptions`, + `RetryBudgetPlugin`. +- `timeout`, `TimeoutOptions`, `TimeoutPlugin`, `TimeoutError`. + +## @monarcode/effetch/test + +`@monarcode/effetch/test` exports the `FetchTest` namespace, covered in +[testing](/docs/testing). + +The exports: + +- `layer`, `LayerOptions`, `Handler`, `HandlerServices`. +- `respond`, `RespondRequest`, `RespondResult`, `TestEvent`, `RespondOptions`, + `RespondServices`, `RouteParams`, `RequestBody`, `RequestQuery`, + `QueryParams`, `TestEndpoint`. +- `reply`, `Reply`, `ReplyOptions`. +- `fail`, `FailBody`, `FailServices`. +- `requests`, `Recorder`, `SentRequest`. diff --git a/site/content/docs/(latest)/reference/limitations.mdx b/site/content/docs/(latest)/reference/limitations.mdx index 6472c6c..a9506bd 100644 --- a/site/content/docs/(latest)/reference/limitations.mdx +++ b/site/content/docs/(latest)/reference/limitations.mdx @@ -2,3 +2,36 @@ title: Limitations description: Check a known limit before you rely on it. --- + +This page lists the known limits of Effetch's paths, plugins and streams. +Check one before you rely on the behavior it describes. + +## Paths + +Paths and their parameters have these limits: + +- A path parameter is a whole segment: `/files/:name.json` has one parameter + called `name.json`. +- Path parameters can't be optional. Define one endpoint per path, or pass + the value in `query`. +- Paths shouldn't contain `?` or `#`. Pass query parameters with `query`. + +## Plugins + +Plugins have these limits: + +- `timeout`, and the duration `logger` logs, cover the time until the + response headers arrive, not downloading the body. `consoleLogger`'s + duration, and an `onExit` hook's `durationMs`, include decoding the body. +- Two plugins with the same name are only caught when the client is made. + +## Streams + +Streamed responses have these limits: + +- Streams don't reconnect: `api.sse` ignores `retry:` lines and the + `Last-Event-ID` header. Repeat the call, with the last `id` in a header, + to pick up where a stream stopped. +- For a stream, plugins see the call end when the response's headers + arrive: they don't see the body being read, or a `DecodeError` while + reading it, and `timeout` doesn't bound it. diff --git a/site/content/docs/(latest)/reference/meta.json b/site/content/docs/(latest)/reference/meta.json index a047014..04424f0 100644 --- a/site/content/docs/(latest)/reference/meta.json +++ b/site/content/docs/(latest)/reference/meta.json @@ -1,11 +1,4 @@ { "title": "Reference", - "pages": [ - "index", - "fetch", - "plugins", - "fetch-test", - "limitations", - "compatibility" - ] + "pages": ["index", "limitations"] } diff --git a/site/content/docs/(latest)/reference/plugins.mdx b/site/content/docs/(latest)/reference/plugins.mdx deleted file mode 100644 index ba213de..0000000 --- a/site/content/docs/(latest)/reference/plugins.mdx +++ /dev/null @@ -1,4 +0,0 @@ ---- -title: Plugins -description: Look up a built-in plugin from @monarcode/effetch/plugins. ---- diff --git a/site/content/docs/(latest)/streaming.mdx b/site/content/docs/(latest)/streaming.mdx index 36bf0e4..9692611 100644 --- a/site/content/docs/(latest)/streaming.mdx +++ b/site/content/docs/(latest)/streaming.mdx @@ -2,3 +2,203 @@ title: Streaming responses description: Read Server-Sent Events or newline-delimited JSON as a Stream, and handle how a stream fails or stops. --- + +Some APIs send their answer a piece at a time: progress feeds, +notifications, exports, the answers of language models. `api.sse` and +`api.ndjson` give such a body as an Effect `Stream`, one value at a time, +as it arrives. This page shows how to read both formats, define stream +endpoints, and handle a stream that fails or that you stop. + +## Read Server-Sent Events + +`api.sse` reads a `text/event-stream` body. Each value is an event, with +its `event` name (`"message"` when the server sends none), its `id`, and its +`data`, decoded with `output`: + +```ts +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; + +import type { Fetch } from "@monarcode/effetch"; + +declare const api: Fetch.Client; + +const JobEvent = Schema.Struct({ percent: Schema.Finite }); + +export const followJob = (id: number) => + api.sse("/jobs/:id/events", { params: { id }, output: JobEvent }).pipe( + Stream.takeUntil((event) => event.data.percent === 100), + Stream.runForEach((event) => Effect.log(`${event.data.percent}%`)), + ); +``` + +The following rules apply to an SSE call: + +- `output` decodes each event's `data` as JSON. Without it, or with + `Fetch.text()`, `data` is the text as it was sent. +- `method` defaults to `"GET"`. APIs that stream the answer to a request + take `"POST"` and a `body`: + + ```ts + import * as Schema from "effect/Schema"; + + import type { Fetch } from "@monarcode/effetch"; + + declare const api: Fetch.Client; + + const Prompt = Schema.Struct({ prompt: Schema.String }); + const Delta = Schema.Struct({ text: Schema.String }); + + export const complete = (prompt: string) => + api.sse("/completions", { + method: "POST", + input: Prompt, + body: { prompt }, + output: Delta, + }); + ``` + +- The request sends `Accept: text/event-stream`, unless the call or the + client sets an `accept` header. +- Events are parsed by the + [WHATWG rules](https://html.spec.whatwg.org/multipage/server-sent-events.html): + comment lines are ignored, a multi-line `data` is joined with `\n`, and an + `id` carries over to the events after it. The stream doesn't reconnect, + and ignores `retry:` lines. +- A response whose `Content-Type` is set to another type than + `text/event-stream`, such as a login page from a proxy, fails the stream + with a `DecodeError`. + + + `api.sse` parses events with Effect's `encoding/Sse` module, which Effect + marks unstable. + + +### Stop at a sentinel + +`output` decodes every event, so an event whose data doesn't match it +fails the stream, after the events before it. When the server ends with a +sentinel that isn't JSON, such as `data: [DONE]`, leave `output` out, stop +at the sentinel, then decode the rest: + +```ts +import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; + +import type { Fetch } from "@monarcode/effetch"; + +declare const api: Fetch.Client; + +const Delta = Schema.fromJsonString(Schema.Struct({ text: Schema.String })); + +export const deltas = (prompt: string) => + api.sse("/completions", { method: "POST", body: { prompt } }).pipe( + Stream.takeWhile((event) => event.data !== "[DONE]"), + Stream.mapEffect((event) => Schema.decodeUnknownEffect(Delta)(event.data)), + ); +``` + +## Read newline-delimited JSON + +`api.ndjson` reads an `application/x-ndjson` body (also called JSON Lines): +one JSON value per line, decoded with `output`: + +```ts +import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; + +import type { Fetch } from "@monarcode/effetch"; + +declare const api: Fetch.Client; + +const Row = Schema.Struct({ id: Schema.Finite, email: Schema.String }); + +export const countRows = api + .ndjson("/export/users", { output: Row }) + .pipe(Stream.runCount); +``` + +The following rules apply to an NDJSON call: + +- Without `output`, each value is the parsed JSON, typed `unknown`. + `Fetch.text()` gives each line's text instead. +- Blank lines are skipped, and the last line needs no line end. +- The request sends `Accept: application/x-ndjson`, unless an `accept` + header is set. + +## Define a stream endpoint + +An [endpoint](/docs/endpoints) defined with `stream: "sse"` or +`stream: "ndjson"` returns a `Stream` from its calls, however it's bound: + +```ts +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; + +import { Fetch } from "@monarcode/effetch"; + +const JobEvent = Schema.Struct({ percent: Schema.Finite }); + +const jobEvents = Fetch.endpoint("GET /jobs/:id/events", { + output: JobEvent, + stream: "sse", +}); + +class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.example.com", +}) {} + +export class JobApi extends Fetch.Endpoints()("JobApi", Api, { + events: jobEvents, +}) {} + +export const lastEvent = (id: number) => + Effect.gen(function* () { + const jobs = yield* JobApi; + return yield* jobs.events({ params: { id } }).pipe(Stream.runLast); + }); +``` + +## How a stream fails + +A stream's request runs as any call does, up to the response's headers: + +- Plugins run once. `retry` and `timeout` apply to getting the response, + not to reading the body. +- When no response arrives, the stream fails with a `NetworkError`. +- An error status fails it with an `HttpError`, or a + [`statusErrors`](/docs/errors/status-errors) error, before it gives any + value. +- A `204 No Content` or `205 Reset Content` gives an empty stream. + +Then the body is read as it arrives. The values before a failure are given +first. A value that doesn't match `output`, or a body that breaks off, +fails the stream with a `DecodeError`, which names the event or the line: +`Line 3 doesn't match the output schema`. + +For plugins, the call ends when the response's headers arrive. Their +`onExit` hooks, and so `logger` and `consoleLogger`, report it then, with +the time to the headers, and a `DecodeError` while reading the body doesn't +reach them. Handle it on the stream, with `Stream.catchTag("DecodeError", …)` +or `Stream.tapError`. + +## Stop a stream + +Interrupting the stream, or taking only part of it, as with `Stream.take`, +aborts the request. Nothing else is needed to close the connection. + +## Options a stream doesn't take + +A stream can't take `responseMode`, or an `output` made with +`Fetch.bytes()`. A call that passes one dies, and a definition with one +throws when it's made. + +## What's next + +- [Pagination](/docs/pagination): follow a list's pages as a `Stream`. +- [Test stream endpoints](/docs/testing/streams): answer a stream endpoint + from a fake backend. +- [Errors by status](/docs/errors/status-errors): fail a stream with your + own error for a status. diff --git a/site/content/docs/(latest)/structuring-an-app.mdx b/site/content/docs/(latest)/structuring-an-app.mdx index 527cbbd..430d230 100644 --- a/site/content/docs/(latest)/structuring-an-app.mdx +++ b/site/content/docs/(latest)/structuring-an-app.mdx @@ -2,3 +2,241 @@ title: Structure an app description: Lay out clients and endpoints in a small app, a feature-sliced app and an app with several backends. --- + +This page shows where clients and endpoints can live as your app grows, from +a single client to several backends. + +A client is declared once, and endpoints are bound to it once, in a layer. +Where each piece lives depends on the size of your app. These are patterns, +not rules: Effetch works the same way whichever you pick. + +## A small app + +Keep the client in one file, and each area's endpoints in its own file, as a +`Fetch.Endpoints` class. One layer puts them together: + +```ts +import * as Effect from "effect/Effect"; +import * as FetchHttpClient from "effect/http/FetchHttpClient"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; + +import { Fetch } from "@monarcode/effetch"; +import { bearer } from "@monarcode/effetch/plugins"; + +const User = Schema.Struct({ id: Schema.Finite, name: Schema.String }); +const NewUser = Schema.Struct({ name: Schema.String }); +const Todo = Schema.Struct({ id: Schema.Finite, title: Schema.String }); + +// api.ts +export class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.example.com", + plugins: [bearer({ token: "token" })], +}) {} + +// users.ts +export class Users extends Fetch.Endpoints()("Users", Api, { + get: Fetch.endpoint("GET /users/:id", { output: User }), + create: Fetch.endpoint("POST /users", { input: NewUser, output: User }), + login: [ + Fetch.endpoint("POST /auth/login", { output: User }), + { plugins: { bearer: false } }, + ], +}) {} + +// todos.ts +export class Todos extends Fetch.Endpoints()("Todos", Api, { + list: Fetch.endpoint("GET /todos", { output: Schema.Array(Todo) }), +}) {} + +// layer.ts +export const AppLayer = Layer.mergeAll(Users.layer, Todos.layer).pipe( + Layer.provideMerge(Api.layer), + Layer.provide(FetchHttpClient.layer), +); + +// anywhere +export const program = Effect.gen(function* () { + const users = yield* Users; + const api = yield* Api; // for one-off calls + const user = yield* users.get({ params: { id: 1 } }); + yield* api.post("/users/:id/ping", { params: { id: user.id } }); + return user; +}); +``` + +The plugin override on `login` is checked against `Api`'s plugins, and every +endpoint's errors are typed with `Api`'s `defaultError` and `statusErrors`. + +### Endpoints made with client.endpoint + +To make endpoints with `client.endpoint` instead, write each area as a +function of the client, typed `Effect.Success`, so overrides and +errors are still checked against your plugins and `defaultError`: + +```ts +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import { Fetch } from "@monarcode/effetch"; +import { bearer } from "@monarcode/effetch/plugins"; + +const User = Schema.Struct({ id: Schema.Finite, name: Schema.String }); + +class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.example.com", + plugins: [bearer({ token: "token" })], +}) {} + +export const users = (api: Effect.Success) => ({ + get: api.endpoint("GET /users/:id", { output: User }), + login: api.endpoint("POST /auth/login", { + output: User, + plugins: { bearer: false }, + }), +}); +``` + +## A feature-sliced app + +When your app is split into feature modules, each with its own schemas, the +client becomes shared infrastructure that knows nothing about the modules. +Each module defines its endpoints next to its schemas, with no client, and +binds them to the client in its data layer: + +```text +src/ +├── infrastructure/http/ +│ └── app-api-client.ts the client: base URL, error body, plugins +├── modules/ +│ ├── todos/ +│ │ ├── contract/ schemas, and endpoints defined with Fetch.endpoint +│ │ ├── data/ the endpoints, bound to AppApiClient +│ │ ├── application/ workflows that take more than one call +│ │ └── public.ts +│ └── wallet/ +└── runtime.ts modules, on top of clients, on top of HttpClient +``` + + + **This layout is a personal preference,** the one Effetch's author uses in + their own apps, and Effetch doesn't depend on it. Rename, merge or split the + folders to suit your project. What carries over is that modules import the + client, never the other way around, and that endpoints are bound once, in a + layer. + + +The following code shows each file of the layout, with the `todos` module: + +```ts +import * as Config from "effect/Config"; +import * as Effect from "effect/Effect"; +import * as FetchHttpClient from "effect/http/FetchHttpClient"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; + +import { Fetch } from "@monarcode/effetch"; + +// infrastructure/http/app-api-client.ts: how to reach the backend, nothing else +export class AppApiClient extends Fetch.Service()( + "AppApiClient", + { baseUrl: Config.String("APP_API_URL") }, +) {} + +// modules/todos/contract/todos.ts: schemas and endpoints, no client +const Todo = Schema.Struct({ id: Schema.Finite, title: Schema.String }); +const NewTodo = Schema.Struct({ title: Schema.String }); + +export const listTodos = Fetch.endpoint("GET /todos", { + output: Schema.Array(Todo), +}); +export const getTodo = Fetch.endpoint("GET /todos/:id", { output: Todo }); +export const createTodo = Fetch.endpoint("POST /todos", { + input: NewTodo, + output: Todo, +}); + +// modules/todos/data/todo.api.ts: the endpoints, bound, as the module's service +export class TodoApi extends Fetch.Endpoints()( + "TodoApi", + AppApiClient, + { + list: listTodos, + get: getTodo, + create: createTodo, + }, +) {} + +// runtime.ts +export const AppLayer = TodoApi.layer.pipe( + Layer.provideMerge(AppApiClient.layer), + Layer.provide(FetchHttpClient.layer), +); + +// anywhere +export const program = Effect.gen(function* () { + const todos = yield* TodoApi; + const todo = yield* todos.create({ body: { title: "Write docs" } }); + return yield* todos.get({ params: { id: todo.id } }); +}); +``` + +### Why this layout scales + +This scales well as the app grows: + +- **The client file stays the same size,** however many endpoints the app + has, and it never imports a module: dependencies point from the modules to + the infrastructure. +- **A module with 20 endpoints has 20 definitions** in its own `contract/` + folder, beside their schemas, and 20 one-line entries in its + `Fetch.Endpoints` class in `data/`. When they serve separate concerns, + split them into several services, each in its own file. +- **Every module's data service is its endpoints,** as `TodoApi` is here: one + line per operation, and every type inferred, so every module's `data/` + folder looks the same. +- **An operation that isn't one HTTP call** (it combines calls, reshapes a + response or adds a domain error) is a workflow over those endpoints, in the + module's `application/` folder. +- **Declare a service's interface by hand only when you need another + implementation,** such as an offline one or a fake for UI work, and + implement it with the endpoints. + +### client.endpoint in this layout + +`client.endpoint` fits this layout too: make the endpoints in `data/`, and +import only the schemas from `contract/`. Define them with `Fetch.endpoint` +when something should read the routes and schemas without a client. +[`examples/app`](https://github.com/monarcode/effetch/tree/main/examples/app) +is a complete app in this layout, with two modules and two backends: `todos` +declares its definitions with `Fetch.Endpoints`, and `wallet` uses +`client.endpoint`. + +## Several backends + +Declare one client per backend, each with its own id, `baseUrl`, +`defaultError` and plugins. Each module uses the client of the backend it +talks to, and one `HttpClient` layer serves them all. + +Keep the following in mind: + +- Plugins are values: one `bearer` can serve several clients. +- `ctx.route` has no host. A plugin that groups by route and is shared by + several clients should take the backend's name, so each client gets its own + instance. +- Catch a backend's `HttpError` next to its calls, where `body` has that + backend's error shape. + +[`examples/backends.ts`](https://github.com/monarcode/effetch/blob/main/examples/backends.ts) +does this in one file, and +[`examples/app`](https://github.com/monarcode/effetch/tree/main/examples/app) +across modules. + +## What's next + +- [Share endpoints as a service](/docs/endpoints/services): see everything + a `Fetch.Endpoints` class gives you. +- [Declare a client](/docs/clients): declare one client per backend, with + its own base URL, errors and plugins. +- [Test with a fake backend](/docs/testing): serve your endpoints from a + fake backend in tests. diff --git a/site/content/docs/(latest)/testing/errors.mdx b/site/content/docs/(latest)/testing/errors.mdx index a5e9a5f..1b793b8 100644 --- a/site/content/docs/(latest)/testing/errors.mdx +++ b/site/content/docs/(latest)/testing/errors.mdx @@ -2,3 +2,95 @@ title: Test errors and statuses description: Make the fake backend fail or answer with another status. --- + +This page shows how to make the [fake backend](/docs/testing) answer with an +error, or with another status, so you can test how your code +handles each one. + +## Fail every request to an endpoint + +To answer every request to an endpoint with an error, use `FetchTest.fail`, +with a status and an optional body. The body is encoded with the endpoint's +`statusErrors` schema for that status, then its `error` schema, so the client +decodes it back into your domain error: + +```ts +import * as Schema from "effect/Schema"; + +import { Fetch } from "@monarcode/effetch"; +import { FetchTest } from "@monarcode/effetch/test"; + +class TodoNotFound extends Schema.TaggedError()("TodoNotFound", { + message: Schema.String, +}) {} + +const getTodo = Fetch.endpoint("GET /todos/:id", { + statusErrors: { 404: TodoNotFound }, +}); + +export const Backend = FetchTest.layer([ + // The call fails with a TodoNotFound. + FetchTest.fail(getTodo, 404, new TodoNotFound({ message: "No todo 9" })), +]); +``` + +## Answer with another status + +A handler answers with another status by returning +`FetchTest.reply(status, body)`, such as a `404` for one id and the todo for +the others. A reply's body is sent as it is, as a call's `body` without +`input` is: + +- no body +- a string as text +- bytes as bytes +- a `Blob`, `FormData` or `URLSearchParams` as it is +- anything else as JSON + +For a `2xx` with a typed body, such as a `201`, pass `{ status: 201 }` as +`respond`'s third argument instead. + +The following backend answers `404` for every todo but the first, and `201` +with a `location` header when a todo is created: + +```ts +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import { Fetch } from "@monarcode/effetch"; +import { FetchTest } from "@monarcode/effetch/test"; + +const Todo = Schema.Struct({ id: Schema.Finite, title: Schema.String }); +const getTodo = Fetch.endpoint("GET /todos/:id", { output: Todo }); +const createTodo = Fetch.endpoint("POST /todos", { + input: Schema.Struct({ title: Schema.String }), + output: Todo, +}); + +export const Backend = FetchTest.layer([ + FetchTest.respond(getTodo, ({ params }) => + Effect.succeed( + params.id === "1" + ? { id: 1, title: "Write docs" } + : FetchTest.reply(404, { message: `No todo ${params.id}` }), + ), + ), + FetchTest.respond( + createTodo, + ({ body }) => Effect.succeed({ id: 2, ...body }), + { + status: 201, + headers: { location: "/todos/2" }, + }, + ), +]); +``` + +## What's next + +- [Errors by status](/docs/errors/status-errors): declare the domain errors + that `FetchTest.fail` encodes. +- [Check what was sent](/docs/testing/requests): assert on the requests your + code sent. +- [Use a hand-written HttpClient](/docs/testing/http-client): fake a network + failure, which the fake backend doesn't do. diff --git a/site/content/docs/(latest)/testing/http-client.mdx b/site/content/docs/(latest)/testing/http-client.mdx index 4d52d69..1011dca 100644 --- a/site/content/docs/(latest)/testing/http-client.mdx +++ b/site/content/docs/(latest)/testing/http-client.mdx @@ -1,4 +1,64 @@ --- title: Use a hand-written HttpClient -description: Fake the transport with your own HttpClient. +description: Fake the transport with your own HttpClient for what a fake backend doesn't do. --- + +This page shows how to provide an `HttpClient` of your own in tests, for what +a [fake backend](/docs/testing) doesn't do, such as a network failure or a +slow response. + +## Provide your own HttpClient + +Effetch sends every request through the `HttpClient` layer you provide, so a +test can provide one that answers however you need. The following client +records each request and answers with a todo: + +```ts +import * as Effect from "effect/Effect"; +import * as HttpClient from "effect/http/HttpClient"; +import * as HttpClientResponse from "effect/http/HttpClientResponse"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; + +import { Fetch } from "@monarcode/effetch"; + +const Todo = Schema.Struct({ id: Schema.Finite, title: Schema.String }); + +class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.test", +}) {} + +const sent: Array = []; + +const TestHttpClient = Layer.succeed( + HttpClient.HttpClient, + HttpClient.make((request, url) => { + sent.push(`${request.method} ${url.href}`); + return Effect.succeed( + HttpClientResponse.fromWeb( + request, + Response.json({ id: 1, title: "Write docs" }), + ), + ); + }), +); + +const program = Effect.gen(function* () { + const api = yield* Api; + return yield* api.get("/todos/:id", { params: { id: 1 }, output: Todo }); +}); + +const todo = await Effect.runPromise( + program.pipe(Effect.provide(Api.layer.pipe(Layer.provide(TestHttpClient)))), +); +// todo: { id: 1, title: "Write docs" }; sent: ["GET https://api.test/todos/1"] +``` + +## What's next + +- [Test with a fake backend](/docs/testing): answer requests from your + endpoints, with typed handlers. +- [Test stream endpoints](/docs/testing/streams): fake a stream whose whole + body arrives at once. +- [Platform notes](/docs/platforms): the `HttpClient` setup each platform + needs. diff --git a/site/content/docs/(latest)/testing/index.mdx b/site/content/docs/(latest)/testing/index.mdx index 2f0a023..951a0cf 100644 --- a/site/content/docs/(latest)/testing/index.mdx +++ b/site/content/docs/(latest)/testing/index.mdx @@ -2,3 +2,139 @@ title: Test with a fake backend description: Test calls against a fake backend made from your endpoints. --- + +This tutorial builds a fake backend from your endpoints and runs a call +against it, so you can test your code without a network. + +Effetch never touches the network itself: it sends every request through the +`HttpClient` you provide. In tests, `@monarcode/effetch/test` gives you a fake +one, made from your endpoints, so your code runs as it does in production: +the real client, with its plugins, `defaultError` and `statusErrors`. + +## Build a fake backend from your endpoints + +`FetchTest.layer` takes a list of handlers, one per route, and is an +`HttpClient` layer. Provide it where `FetchHttpClient.layer` goes. + + + A client whose `layer` is + [overridden](/docs/clients/providing#build-the-httpclient-into-the-layer) to + provide its own `HttpClient` ignores the fake backend, so test with a layer + that doesn't. + + +The following example defines three endpoints, answers each one from the fake +backend, and gets a todo through the real client: + +```ts +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; + +import { Fetch } from "@monarcode/effetch"; +import { FetchTest } from "@monarcode/effetch/test"; + +const Todo = Schema.Struct({ + id: Schema.Finite, + title: Schema.String, + due: Schema.Date, +}); +const NewTodo = Schema.Struct({ title: Schema.String, due: Schema.Date }); + +class TodoNotFound extends Schema.TaggedError()("TodoNotFound", { + message: Schema.String, +}) {} + +const getTodo = Fetch.endpoint("GET /todos/:id", { + output: Todo, + statusErrors: { 404: TodoNotFound }, +}); +const createTodo = Fetch.endpoint("POST /todos", { + input: NewTodo, + output: Todo, +}); +const listTodos = Fetch.endpoint("GET /todos", { output: Schema.Array(Todo) }); + +class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.test", +}) {} + +class TodoApi extends Fetch.Endpoints()("TodoApi", Api, { + get: getTodo, + create: createTodo, + list: listTodos, +}) {} + +const Backend = FetchTest.layer([ + FetchTest.respond(getTodo, ({ params }) => + // params are strings, as they are in the URL + Effect.succeed({ + id: Number(params.id), + title: "Write docs", + due: new Date(0), + }), + ), + FetchTest.respond(createTodo, ({ body }) => + Effect.succeed({ id: 2, ...body }), + ), + FetchTest.fail(listTodos, 503), +]); + +const TestLayer = TodoApi.layer.pipe( + Layer.provide(Api.layer), + Layer.provide(Backend), +); + +export const test = Effect.gen(function* () { + const todos = yield* TodoApi; + const todo = yield* todos.get({ params: { id: 1 } }); + // todo.due is a Date again: it went over the wire as a string + return todo; +}).pipe(Effect.provide(TestLayer)); +``` + +## What a handler gets and returns + +What a handler gets and returns is typed by its endpoint, and checked as a +real backend would check it: + +- **`params`** has the route's params, as strings. +- **`body`** is decoded with the endpoint's `input` schema, so `body.due` is a + `Date` here. A [multipart](/docs/calls/uploads) body is read back from the + form, with its files as `File`s. +- **`query`** is decoded with the endpoint's + [query schema](/docs/endpoints/typed-query), if it has one, and is the raw + query, as strings, otherwise. +- **The result** has `output`'s type, and is encoded with `output` before + it's sent, so a `Date` goes over the wire as a string, as in production. + With [`Fetch.text()` or `Fetch.bytes()`](/docs/calls/responses), it's sent + as text or bytes. + +A body, query or result that doesn't match its schema is a defect that names +the route: it's a bug in the code under test, or in the test. Handlers work +the same for definitions made with `Fetch.endpoint`, endpoints made with +`client.endpoint` or `client.bind`, and a `Fetch.Endpoints` class's +`definitions`. + +### Handlers that use services + +A handler can use services, such as a clock or a store of fake data. The +layer then needs them, and runs its handlers with the services it was built +with, and those of the call they answer, which win when both have one. + +## Run the test + +`FetchTest` doesn't depend on a test runner: a test is an Effect, so run it +with `it.effect` from `@effect/vitest`, or with `Effect.runPromise` in Jest, +Bun or Deno. + +## What's next + +- [Test errors and statuses](/docs/testing/errors): make the fake backend + fail, or answer with another status. +- [Check what was sent](/docs/testing/requests): assert on the requests your + code sent, and see how routes match them. +- [Test stream endpoints](/docs/testing/streams): answer a stream endpoint + with a list of events or values. +- [Use a hand-written HttpClient](/docs/testing/http-client): fake a network + failure or a slow response. diff --git a/site/content/docs/(latest)/testing/requests.mdx b/site/content/docs/(latest)/testing/requests.mdx index d19805a..968181b 100644 --- a/site/content/docs/(latest)/testing/requests.mdx +++ b/site/content/docs/(latest)/testing/requests.mdx @@ -2,3 +2,81 @@ title: Check what was sent description: Assert on the requests your code sent, and learn how they're matched. --- + +This page shows how to read the requests the [fake backend](/docs/testing) +received, so you can assert on what your code sent, and explains how the +fake backend matches each request to a handler. + +## Read the recorded requests + +The layer also provides `FetchTest.Recorder`, which keeps every request it +received, with a new record each time the layer is built. +`FetchTest.requests` reads it. Under a client's layer, `Layer.provide` would +hide it, so use `Layer.provideMerge`: + +```ts +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import { Fetch } from "@monarcode/effetch"; +import { FetchTest } from "@monarcode/effetch/test"; + +class Api extends Fetch.Service()("Api", { + baseUrl: "https://api.test", +}) {} + +const deleteTodo = Fetch.endpoint("DELETE /todos/:id"); + +const Backend = FetchTest.layer([ + FetchTest.respond(deleteTodo, () => Effect.void), +]); + +export const test = Effect.gen(function* () { + const api = yield* Api; + yield* api.bind(deleteTodo)({ params: { id: 1 } }); + const [sent] = yield* FetchTest.requests; + // sent.method: "DELETE", sent.url: "https://api.test/todos/1", + // sent.route: "DELETE /todos/:id", sent.params: { id: "1" } + return sent; +}).pipe(Effect.provide(Api.layer.pipe(Layer.provideMerge(Backend)))); +``` + +Each recorded request has its `method`, `url`, the `route` and `params` it +matched, its raw `query`, its `headers`, and its `body`, read back as JSON, +text or bytes. + +## How requests are matched + +The fake backend picks a handler for each request by these rules: + +- **Method and path.** A route matches a request with the same method, whose + path ends with the route's path. So `GET /todos/:id` answers + `https://api.test/v1/todos/1`, whatever the client's `baseUrl`. To match + the whole URL instead, pass the `baseUrl` to the layer: + `FetchTest.layer(handlers, { baseUrl: "https://api.test/v1" })`. +- **The root route,** `GET /`, matches the path `/` alone, since every path + with a trailing slash ends with it. Under a `baseUrl` with a path, pass + that `baseUrl` to the layer. +- **The best match wins.** When several routes match, the one with the most + segments wins, then the one with the most literal segments, so + `GET /todos/count` wins over `GET /todos/:id`. After that, the one listed + first wins. +- **Absolute routes** such as `POST https://uploads.example.com/files` match + that URL only. +- **No match is a defect,** whose message lists the backend's routes, and the + ones that match the path with another method: + + ```text + FetchTest: no handler for POST https://api.test/todos/1. + GET /todos/:id matches its path, but not its method. + The handlers are: + - GET /todos/:id + ``` + +## What's next + +- [Test errors and statuses](/docs/testing/errors): make the fake backend + fail, or answer with another status. +- [Use a hand-written HttpClient](/docs/testing/http-client): fake what the + fake backend doesn't do, such as a network failure. +- [Entry points](/docs/reference): every export of `FetchTest`. diff --git a/site/content/docs/(latest)/testing/streams.mdx b/site/content/docs/(latest)/testing/streams.mdx index a32f1ec..03bc736 100644 --- a/site/content/docs/(latest)/testing/streams.mdx +++ b/site/content/docs/(latest)/testing/streams.mdx @@ -1,4 +1,60 @@ --- title: Test stream endpoints -description: Fake a streamed response. +description: Fake a streamed response with a list of events or values. --- + +This page shows how to answer a [stream endpoint](/docs/streaming) from the +[fake backend](/docs/testing), so you can test code that reads Server-Sent +Events or newline-delimited JSON. + +## Answer with a list + +A handler for a stream endpoint returns a list, and `FetchTest` sends it as +the stream's body: + +- For `stream: "sse"`, the list holds events, each with its `data` and an + optional `event` and `id`. +- For `stream: "ndjson"`, the list holds values. + +Each value is encoded with the endpoint's `output`. The following backend +sends two events for a job: + +```ts +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import { Fetch } from "@monarcode/effetch"; +import { FetchTest } from "@monarcode/effetch/test"; + +const JobEvent = Schema.Struct({ percent: Schema.Finite }); + +const jobEvents = Fetch.endpoint("GET /jobs/:id/events", { + output: JobEvent, + stream: "sse", +}); + +export const Backend = FetchTest.layer([ + FetchTest.respond(jobEvents, ({ params }) => + Effect.succeed([ + { data: { percent: 50 } }, + { event: "done", id: params.id, data: { percent: 100 } }, + ]), + ), +]); +``` + +## Test slow or broken streams + +The whole body is sent at once. To test how your code handles values that +arrive slowly, or a body that breaks off, use +[a hand-written `HttpClient`](/docs/testing/http-client) whose `Response` +has a `ReadableStream` body. + +## What's next + +- [Streaming responses](/docs/streaming): how stream endpoints read events + and values, and how a stream fails. +- [Use a hand-written HttpClient](/docs/testing/http-client): send a body + that arrives slowly or breaks off. +- [Check what was sent](/docs/testing/requests): assert on the requests your + code sent. diff --git a/site/content/docs/(latest)/upgrading.mdx b/site/content/docs/(latest)/upgrading.mdx index 5326c62..df007de 100644 --- a/site/content/docs/(latest)/upgrading.mdx +++ b/site/content/docs/(latest)/upgrading.mdx @@ -2,3 +2,82 @@ title: Upgrade from 0.1.0-rc.3 description: Move a project's imports to the Fetch namespace with the effetch-migrate command. --- + +This page shows how to move a project written for 0.1.0-rc.3 or earlier to +the `Fetch` export, with the `effetch-migrate` command. + +Before 0.1.0-rc.4, the main entry exported each API by name, and you +imported it with `import * as Fetch`. Since 0.1.0-rc.4, everything in the +main entry is under one export, `Fetch` (see +[Installation](/docs/installation)). + +## Before you begin + +Upgrade the project's `@monarcode/effetch` dependency first. Then run the +commands on this page in the directory of the package that depends on +Effetch. The commands use `npx`; with pnpm, run `pnpm exec effetch-migrate` +instead. + +## Preview the changes + +To list the files the migration would change, without changing them, run +the following command: + +```bash +npx -p @monarcode/effetch effetch-migrate --dry-run +``` + +## Run the migration + +To change the files, run the following command: + +```bash +npx -p @monarcode/effetch effetch-migrate +``` + +The migration makes these changes: + +- `import * as Fetch from "@monarcode/effetch"` becomes + `import { Fetch } from "@monarcode/effetch"`. +- Named imports, such as `import { HttpError, type Client }`, become + `import { Fetch }`, and each use becomes `Fetch.HttpError` or + `Fetch.Client`. +- `export … from "@monarcode/effetch"` re-exports from + `@monarcode/effetch/Fetch`, and `import("@monarcode/effetch").Client` + types become `import("@monarcode/effetch").Fetch.Client`. +- Code that already imports `Fetch` is left as it is. + +## Choose the files it reads + +The migration reads `.ts`, `.tsx`, `.js` and similar files, and uses the +project's own TypeScript. Which files it reads depends on where it runs: + +- In a git repository, it reads the files git sees, so it skips what + `.gitignore` does. +- Elsewhere, it skips `node_modules`, `dist`, `build`, `coverage` and hidden + directories, and lists the build output it skipped. + +To choose what it reads, pass paths, such as `effetch-migrate src test`. + +## Change the rest by hand + +The migration lists, with their lines, what it can't rewrite. Change these +by hand: + +- a dynamic `import()`; +- a `vi.mock("@monarcode/effetch")`; +- an import inside a `declare module` block; +- JSDoc comments that use the old names. + +The migration doesn't read Markdown. + +## Finish the migration + +After the migration, run your formatter and type checker. + +## What's next + +- [Installation](/docs/installation): see the entry points Effetch has now + and how to import from them. +- [Getting started](/docs/getting-started): write a complete program with + the `Fetch` export. diff --git a/site/src/components/mdx.tsx b/site/src/components/mdx.tsx index 6cc428c..c2c61d5 100644 --- a/site/src/components/mdx.tsx +++ b/site/src/components/mdx.tsx @@ -1,3 +1,4 @@ +import { Accordion, Accordions } from "fumadocs-ui/components/accordion"; import { Step, Steps } from "fumadocs-ui/components/steps"; import { Tab, Tabs } from "fumadocs-ui/components/tabs"; import defaultMdxComponents from "fumadocs-ui/mdx"; @@ -6,6 +7,8 @@ import type { MDXComponents } from "mdx/types"; export function getMDXComponents(components?: MDXComponents) { return { ...defaultMdxComponents, + Accordion, + Accordions, Step, Steps, Tab,