# Pagination (https://effetch.pages.dev/docs/pagination)

Lists are often split into pages: you ask for the first, and the response
says how to get the next. Writing that loop by hand for every list means
tracking the state, stopping at the end, and not fetching pages nobody
reads. `Fetch.paginate` follows the 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>()("Api", {
  baseUrl: "https://api.example.com",
}) {}

class TodoApi extends Fetch.Endpoints<TodoApi>()("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: (items, page) =>
      items.length === 0 ? Option.none() : Option.some(page + 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 options for that page's call: `params`,
  `query`, `body` and `headers`, typed by the endpoint. Plugin overrides
  aren't among them, so give those when you bind the endpoint, and every
  page's call uses them. The endpoint's `responseMode` always decides what
  each page is.
- **`next(page, state, response)`** gives the next page's state, or
  `Option.none()` after the last page. `response` is the page's
  `HttpClientResponse` when the endpoint's `responseMode` is
  `"decoded-and-response"`, and `undefined` otherwise.

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`, `api.bind`,
`api.bindAll` or `api.endpoint`. It throws when you pass it a definition
made by `Fetch.endpoint`, which needs binding first, or a stream endpoint,
which can't be paged.

## Read the cursor from a header

Some APIs put the next page's cursor in a header, such as a `Link` header,
rather than in the body. For those, define the endpoint with
`responseMode: "decoded-and-response"`, and `next` 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),
});
```

Each page is still the decoded body, here the array of items. Only `next`
gets the response.

## What's next

- [Call an endpoint](https://effetch.pages.dev/docs/endpoints/calling): bind an endpoint so
  `Fetch.paginate` can call it.
- [Typed query parameters](https://effetch.pages.dev/docs/endpoints/typed-query): type the page or
  cursor that `request` sends.
- [Streaming responses](https://effetch.pages.dev/docs/streaming): read a body that arrives a piece at
  a time.