Page
Import the types used in annotations from tyrus:db. In particular, import Page explicitly whenever a function signature uses the paginated result type.
interface Page<T> {
readonly items: T[];
readonly total: u64;
readonly pageSize: u64;
readonly page?: u64;
readonly totalPages?: u64;
readonly nextCursor?: string;
readonly hasMore?: boolean;
}Numbered pagination returns items, total, pageSize, page, and totalPages. Cursor pagination returns items, total, pageSize, and hasMore, plus nextCursor when another page is available. Fields for the inactive pagination mode are omitted.
The page rows and total are read from the same transaction snapshot across relational backends, so concurrent writes cannot make the count and items describe different database states. MongoDB uses its generated _id for stable ordering; count and item reads are separate operations, so concurrent writes may affect consistency between them. Its cursor token is the serialized 24-character ObjectId of the last returned item; pass nextCursor unchanged to after.
Numbered pagination example
Pass the page number with paginate: true. The first page is page 1; use the returned totalPages to determine whether more numbered pages are available.
import { DbError, Page } from "tyrus:db";
import { User } from "./models/User";
async function listUsersPage(page: u64): Promise<Result<Page<User>, DbError>> {
const data = await User.findMany({}, { paginate: true, pageSize: 25, page }) onfail {
return Err(data);
};
return Ok(data);
}
// Example result for page 1:
// {
// items: [{ id: 1, name: "Ada" }, ...],
// total: 64,
// pageSize: 25,
// page: 1,
// totalPages: 3
// }Cursor pagination example
Omit after to fetch the first page. Pass its nextCursor unchanged as after to fetch the next page. The cursor is the serialized value of the last returned row's @id, not an item count or page number. For an integer @id, "25" means continue after the row whose id is 25; after: "10" starts after id 10, not at the tenth result. Do not calculate the cursor from pageSize.
import { DbError, Page } from "tyrus:db";
import { User } from "./models/User";
async function listFirstUsersCursorPage(): Promise<Result<Page<User>, DbError>> {
const data = await User.findMany({}, { paginate: true, pageSize: 25, cursor: true }) onfail {
return Err(data);
};
return Ok(data);
}
// Example result when another page is available:
// {
// items: [{ id: 1, name: "Ada" }, ...],
// total: 64,
// pageSize: 25,
// hasMore: true,
// nextCursor: "25"
// }
async function listNextUsersCursorPage(after: string): Promise<Result<Page<User>, DbError>> {
const data = await User.findMany({}, { paginate: true, pageSize: 25, cursor: true, after }) onfail {
return Err(data);
};
return Ok(data);
}
// Example result for the next page:
// {
// items: [{ id: 26, name: "Grace" }, ...],
// total: 64,
// pageSize: 25,
// hasMore: true,
// nextCursor: "50"
// }
// On the final page, hasMore is false and nextCursor is omitted.