forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiB5fcd955Burak Boduroğlu2 months ago730 commits

list-page.ts38 lines, 1.2 KiBHistoryRawDownload
1import type { Page, PageParams } from "@/api/client";
2
3export type ListPageState<T> = {
4 items: T[];
5 total: number;
6};
7
8/** Server page when `clientMode` is false; full fetch + caller-supplied filter when true. */
9export async function loadListPage<T>(options: {
10 page: number;
11 pageSize: number;
12 clientMode: boolean;
13 fetch: (params?: PageParams) => Promise<Page<T>>;
14 filter?: (items: T[]) => T[];
15}): Promise<ListPageState<T>> {
16 if (options.clientMode) {
17 const all = await options.fetch();
18 const source = Array.isArray(all.items) ? all.items : [];
19 const filtered = options.filter ? options.filter(source) : source;
20 const start = options.page * options.pageSize;
21 return {
22 items: filtered.slice(start, start + options.pageSize),
23 total: filtered.length,
24 };
25 }
26
27 const result = await options.fetch({
28 limit: options.pageSize,
29 offset: options.page * options.pageSize,
30 });
31 const items = Array.isArray(result.items) ? result.items : [];
32 const total = typeof result.total === "number" ? result.total : items.length;
33 return { items, total };
34}
35
36export function totalPages(total: number, pageSize: number): number {
37 return Math.max(1, Math.ceil(Math.max(0, total) / pageSize));
38}