Foxnouns.NET/Foxnouns.Frontend/src/routes/+layout.server.ts

22 lines
813 B
TypeScript
Raw Normal View History

import { clearToken, TOKEN_COOKIE_NAME } from "$lib";
import { apiRequest } from "$api";
import ApiError, { ErrorCode } from "$api/error";
2024-11-24 17:36:02 +01:00
import type { Meta, MeUser } from "$api/models";
import log from "$lib/log";
import type { LayoutServerLoad } from "./$types";
export const load = (async ({ fetch, cookies }) => {
2024-11-24 17:36:02 +01:00
let meUser: MeUser | null = null;
if (cookies.get(TOKEN_COOKIE_NAME)) {
try {
2024-11-24 17:36:02 +01:00
meUser = await apiRequest<MeUser>("GET", "/users/@me", { fetch, cookies });
} catch (e) {
if (e instanceof ApiError && e.code === ErrorCode.AuthenticationRequired) clearToken(cookies);
else log.error("Could not fetch /users/@me and token has not expired:", e);
}
}
const meta = await apiRequest<Meta>("GET", "/meta", { fetch, cookies });
return { meta, meUser };
}) satisfies LayoutServerLoad;