Files
jamoke/src/lib/server/requestTools.ts

47 lines
838 B
TypeScript

import type { LocalCredentials } from "./auth";
export enum ResourceId {
Game = "gameid",
}
export function getUser(locals: { user: LocalCredentials }) {
// SvelteKit screws up this type somehow, and it's important to explicitely set it
// here.
const user: LocalCredentials = locals.user;
if (user.kind !== "Bearer") {
throw new Error("bad user information");
}
return user;
}
export function getParam(params: Partial<Record<string, string>>, resource: ResourceId) {
const id = params[resource];
if (!id) {
return null;
}
return id;
}
export async function getBody<T>(
request: Request,
dataGuard: (body: unknown) => body is T,
) {
let body: unknown;
try {
body = await request.json();
} catch (err) {
return null;
}
if (!dataGuard(body)) {
throw new Error("data guard failed");
}
return body;
}