mirror of
https://github.com/shuaiplus/nodewarden.git
synced 2026-06-20 21:00:41 +00:00
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:
@@ -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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user