Pagination
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:
import * as from "effect/Effect";
import * as from "effect/Option";
import * as from "effect/Schema";
import * as from "effect/Stream";
import { } from "@monarcode/effetch";
const = .({ : ., : . });
const = .("GET /todos", {
: .({ : . }),
: .(),
});
class extends .<>()("Api", {
: "https://api.example.com",
}) {}
class extends .<>()("TodoApi", , {
: ,
}) {}
export const = .(function* () {
const = yield* ;
return yield* .(., {
: 1,
: () => ({ : { } }),
: (, ) =>
. === 0 ? .() : .( + 1),
}).(., .);
});Fetch.paginate takes three options:
startis the state of the first page, such as a page number or a cursor.request(state)gives the page's call options:params,query,bodyandheaders, typed by the endpoint.next(page, state, response)gives the next page's state, orOption.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:
import * as from "effect/Option";
import * as from "effect/Schema";
import { } from "@monarcode/effetch";
declare const : .;
const = .({ : . });
const = .("GET /items", {
: .(),
: "decoded-and-response",
});
// The cursor is percent-encoded in the URL, and `query` encodes it again.
const = (: string | undefined) =>
.(
/[?&]cursor=([^&>]+)[^>]*>;\s*rel="next"/.( ?? "")?.[1],
).(.(.()));
export const = .(.(), {
: as string | undefined,
: () => ( === ? {} : { : { } }),
: (, , ) => (..),
});What's next
- Call an endpoint: bind an endpoint so
Fetch.paginatecan call it. - Typed query parameters: type the page or
cursor that
requestsends. - Streaming responses: read a body that arrives a piece at a time.