hezarfen_frontend
Clone
https://git.tahinli.com/archive/hezarfen_frontend.git
0 watching0 forksTypeScript5.5 MiB5fcd955Burak Boduroğlu2 months ago730 commits
| 1 | import type { Page, PageParams } from "@/api/client"; |
| 2 | |
| 3 | export 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. */ |
| 9 | export 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 | |
| 36 | export function totalPages(total: number, pageSize: number): number { |
| 37 | return Math.max(1, Math.ceil(Math.max(0, total) / pageSize)); |
| 38 | } |