2026-06-09 19:46:08 +07:00
|
|
|
import { createChildLogger } from "@bete/shared/logger";
|
|
|
|
|
|
|
|
|
|
const logger = createChildLogger("pagination");
|
|
|
|
|
|
2026-06-01 21:44:29 +07:00
|
|
|
export interface CursorData {
|
|
|
|
|
created_at: number;
|
|
|
|
|
id: string;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function encodeCursor(data: CursorData): string {
|
2026-06-09 19:46:08 +07:00
|
|
|
const encoded = Buffer.from(JSON.stringify(data)).toString("base64");
|
|
|
|
|
logger.debug({ id: data.id, createdAt: data.created_at }, "Encoded cursor");
|
|
|
|
|
return encoded;
|
2026-06-01 21:44:29 +07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function decodeCursor(cursor?: string): CursorData | null {
|
2026-06-09 19:46:08 +07:00
|
|
|
if (!cursor) {
|
|
|
|
|
logger.debug("No cursor provided to decode");
|
|
|
|
|
return null;
|
|
|
|
|
}
|
2026-06-01 21:44:29 +07:00
|
|
|
try {
|
|
|
|
|
const data = JSON.parse(Buffer.from(cursor, "base64").toString("utf-8"));
|
|
|
|
|
if (typeof data.created_at === "number" && typeof data.id === "string") {
|
2026-06-09 19:46:08 +07:00
|
|
|
logger.debug(
|
|
|
|
|
{ id: data.id, createdAt: data.created_at },
|
|
|
|
|
"Decoded cursor",
|
|
|
|
|
);
|
2026-06-01 21:44:29 +07:00
|
|
|
return data;
|
|
|
|
|
}
|
2026-06-09 19:46:08 +07:00
|
|
|
logger.warn({ cursor }, "Decoded cursor has invalid shape");
|
2026-06-01 21:44:29 +07:00
|
|
|
return null;
|
2026-06-09 19:46:08 +07:00
|
|
|
} catch (err) {
|
|
|
|
|
logger.warn({ cursor, error: String(err) }, "Failed to decode cursor");
|
2026-06-01 21:44:29 +07:00
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
}
|