Function: paginator()
paginator<
Options,T>(options,handler):Promise<PaginationResultDTO<T,T[]>>
Fetch a page of items with a handler, and build the paginated result: the items, with the page metadata (count the number of items returned, total the handler's total, and the limit and offset of the search). It does not validate the search: pass a validated PaginationSearchDTO (the input of an action, or a constructed DTO), whose limit and offset have their defaults (10 and 0).
Type Parameters
Options
Options extends PaginationSearchDTO
T
T
Parameters
options
Options
The search, a PaginationSearchDTO or a subclass carrying the search criteria.
handler
(limit, offset, options) => Promise<PaginatorHandlerResult<T>>
A function receiving the limit, the offset and the whole search, and resolving to the page of items and the total; its rejection rejects the paginator.
Returns
Promise<PaginationResultDTO<T, T[]>>
A promise of the paginated result (a plain object shaped as PaginationResultDTO).
Example
import {DTO} from 'lakutata'
import {Expect} from 'lakutata/decorator/dto'
import {PaginationResultDTO, PaginationSearchDTO, paginator} from 'lakutata/dtos'
class UserSearchDTO extends PaginationSearchDTO {
@Expect(DTO.String().optional())
public name?: string
}
interface User {
id: number
name: string
}
declare const db: {
countUsers(name?: string): Promise<number>
findUsers(name: string | undefined, limit: number, offset: number): Promise<User[]>
}
export async function SearchUsers(input: Record<string, unknown>): Promise<PaginationResultDTO<User>> {
return await paginator(new UserSearchDTO(input), async (limit: number, offset: number, search: UserSearchDTO) => ({
total: await db.countUsers(search.name),
items: await db.findUsers(search.name, limit, offset)
}))
}