28 lines
1.0 KiB
TypeScript
28 lines
1.0 KiB
TypeScript
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 base64‑encoded 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");
|
||
} |