forked from mtusi2026/mtusi2026lab2
55 lines
1.3 KiB
TypeScript
55 lines
1.3 KiB
TypeScript
import { BadRequestException } from '@nestjs/common';
|
|
|
|
export type Cursor = {
|
|
scope: string;
|
|
created_at: string;
|
|
id: string;
|
|
};
|
|
|
|
export function encodeCursor(cursor: Cursor): string {
|
|
return Buffer.from(JSON.stringify(cursor), 'utf8').toString('base64url');
|
|
}
|
|
|
|
export function decodeCursor(value: string, expectedScope: string): Cursor {
|
|
try {
|
|
const parsed: unknown = JSON.parse(
|
|
Buffer.from(value, 'base64url').toString('utf8'),
|
|
);
|
|
|
|
if (
|
|
typeof parsed !== 'object' ||
|
|
parsed === null ||
|
|
!('scope' in parsed) ||
|
|
!('created_at' in parsed) ||
|
|
!('id' in parsed) ||
|
|
typeof parsed.scope !== 'string' ||
|
|
typeof parsed.created_at !== 'string' ||
|
|
typeof parsed.id !== 'string' ||
|
|
parsed.scope !== expectedScope ||
|
|
parsed.created_at.length === 0 ||
|
|
parsed.id.length === 0
|
|
) {
|
|
throw new Error('invalid cursor');
|
|
}
|
|
|
|
return {
|
|
scope: parsed.scope,
|
|
created_at: parsed.created_at,
|
|
id: parsed.id,
|
|
};
|
|
} catch {
|
|
throw new BadRequestException('Invalid cursor');
|
|
}
|
|
}
|
|
|
|
export function isAfter(
|
|
createdAt: string,
|
|
id: string,
|
|
cursor: Cursor,
|
|
): boolean {
|
|
return (
|
|
createdAt > cursor.created_at ||
|
|
(createdAt === cursor.created_at && id > cursor.id)
|
|
);
|
|
}
|