Files
mtusi2026lab4/src/services/cursor.service.ts
T

46 lines
1.9 KiB
TypeScript

import type { Page } from '../domain/models';
import { invalidRequest } from '../errors/api-error';
import { parseWith } from '../validation/parse';
import { cursorPayloadSchema, paginationSchema, type CursorPayload } from '../validation/schemas';
type CursorScope = Pick<CursorPayload, 'kind' | 'resource'>;
export function encodeCursor(payload: CursorPayload): string {
return Buffer.from(JSON.stringify(payload), 'utf8').toString('base64url');
}
export function decodeCursor(cursor: string): CursorPayload {
try {
const bytes = Buffer.from(cursor, 'base64url');
if (bytes.toString('base64url') !== cursor) throw new Error('Invalid encoding');
return cursorPayloadSchema.parse(JSON.parse(bytes.toString('utf8')));
} catch {
throw invalidRequest('Некорректный cursor');
}
}
export function parsePage(limit: unknown, cursor: unknown, scope: CursorScope) {
if (limit !== undefined && (typeof limit !== 'string' || !/^[0-9]+$/.test(limit))) {
throw invalidRequest('Некорректный limit');
}
const query = parseWith(paginationSchema, { limit: limit === undefined ? undefined : Number(limit), cursor });
const after = query.cursor === undefined ? null : decodeCursor(query.cursor);
if (after && (after.kind !== scope.kind || after.resource !== scope.resource)) {
throw invalidRequest('Cursor не относится к этому списку');
}
return { limit: query.limit, after };
}
export function makePage<T extends { id: string; created_at: string }>(
rows: T[],
limit: number,
scope: CursorScope,
): Page<T> {
const items = rows.slice(0, limit);
const last = items.at(-1);
const next_cursor = last && rows.length > limit
? encodeCursor({ v: 1, ...scope, id: last.id, created_at: new Date(last.created_at).toISOString() })
: null;
return { items, next_cursor };
}