feat(pagination): add pagination utility functions for handling page size and continuation tokens

- Introduced `PaginationRequest` interface to define pagination parameters.
- Implemented `parsePagination` function to extract and validate pagination parameters from a URL.
- Added `encodeContinuationToken` and `decodeContinuationToken` functions for managing continuation tokens.
- Ensured that pagination respects maximum page size limits defined in configuration.
This commit is contained in:
shuaiplus
2026-02-18 20:59:46 +08:00
parent c53819e178
commit b6d4113e21
17 changed files with 668 additions and 232 deletions
+38
View File
@@ -0,0 +1,38 @@
import { LIMITS } from '../config/limits';
const MAX_PAGE_SIZE = LIMITS.pagination.maxPageSize;
export interface PaginationRequest {
limit: number;
offset: number;
}
export function parsePagination(url: URL): PaginationRequest | null {
const pageSizeRaw = url.searchParams.get('pageSize');
const continuationToken = url.searchParams.get('continuationToken');
if (!pageSizeRaw && !continuationToken) return null;
const pageSize = pageSizeRaw ? Number(pageSizeRaw) : LIMITS.pagination.defaultPageSize;
if (!Number.isInteger(pageSize) || pageSize <= 0) return null;
const limit = Math.min(pageSize, MAX_PAGE_SIZE);
const offset = decodeContinuationToken(continuationToken);
return { limit, offset };
}
export function encodeContinuationToken(offset: number): string {
return btoa(String(offset));
}
export function decodeContinuationToken(token: string | null): number {
if (!token) return 0;
try {
const decoded = atob(token);
const offset = Number(decoded);
if (!Number.isInteger(offset) || offset < 0) return 0;
return offset;
} catch {
return 0;
}
}