Files
dsc-api/src/modules/utils/providers/cursor-pagination.utils.ts
T

28 lines
1.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { BadRequestException } from "@nestjs/common";
interface CursorPayload {
priority: number;
createdAt: Date;
id: string;
}
export function decodeCursor(cursor: string): CursorPayload {
try {
const decoded = Buffer.from(cursor, "base64").toString("utf-8");
const [priorityStr, timestamp, id] = decoded.split("|");
if (!priorityStr || !timestamp || !id) throw new Error("Invalid format");
const priority = parseInt(priorityStr, 10);
if (isNaN(priority)) throw new Error("Priority not a number");
const createdAt = new Date(timestamp);
if (isNaN(createdAt.getTime())) throw new Error("Invalid date");
return { priority, createdAt, id };
} catch {
throw new BadRequestException(
"Invalid cursor. Expected base64encoded string containing priority, ISO date and id (separated by '|').",
);
}
}
export function encodeCursor(task: { priority: number; createdAt: Date; id: string }): string {
return Buffer.from(`${task.priority}|${task.createdAt.toISOString()}|${task.id}`).toString("base64");
}