Files
electric-cherry/src/routes/api/leaderboard/+server.ts
T

57 lines
2.1 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 { leaderboardReport } from '$lib/server/reports/index.js';
import { json } from '@sveltejs/kit';
import { isLeaderboardMetric, MAX_LEADERBOARD_OFFSET } from '$lib/server/fleet/leaderboard.js';
import type { LeaderboardPlayerCount } from '$lib/leaderboard.js';
export async function GET({ url }: { url: URL }) {
const params = url.searchParams;
const game = params.get('game');
const map = params.get('map');
const metric = params.get('metric');
const q = params.get('q');
const players = params.get('players');
const rawLimit = params.get('limit');
const rawOffset = params.get('offset');
const integer = (value: string | null, fallback: number) =>
value === null
? fallback
: /^\d+$/.test(value) && Number.isSafeInteger(Number(value))
? Number(value)
: NaN;
const limit = integer(rawLimit, 50);
const offset = integer(rawOffset, 0);
if (
(game !== null && game !== 't5' && game !== 't6') ||
(map !== null && map.length > 1024) ||
(q !== null && q.length > 100) ||
(metric !== null && !isLeaderboardMetric(metric)) ||
(players !== null && !/^[1-4]$/.test(players)) ||
!Number.isFinite(limit) ||
limit < 1 ||
limit > 100 ||
!Number.isFinite(offset) ||
offset < 0 ||
offset > MAX_LEADERBOARD_OFFSET
) {
return json(
{
ok: false,
kind: 'bad-request',
error: 'Use game t5 or t6, a supported metric, players 1–4, map key up to 1024 characters, q up to 100 characters, limit 1–100, and offset 0–1000000.'
},
{ status: 400 }
);
}
return json(
await leaderboardReport({
game: game ?? undefined,
map: map || undefined,
metric: metric !== null && isLeaderboardMetric(metric) ? metric : undefined,
players: players === null ? undefined : (Number(players) as LeaderboardPlayerCount),
q: q ?? undefined,
limit,
offset
})
);
}