Files
jamoke/src/routes/+layout.server.ts

50 lines
1.2 KiB
TypeScript

import { isServerResponse } from "$lib/ServerResponse";
import { redirect, type ServerLoad } from "@sveltejs/kit";
import { isMe, type Me } from "$lib/me";
import { setMeContext } from "$lib/meContext";
export const load: ServerLoad = async ({ request, cookies, fetch }) => {
const url = new URL(request.url);
const token = cookies.get("access_token");
let me: Me | null = null;
if (token) {
const res = await fetch("/api/me", {
headers: [["authorization", token]],
});
const body = await res.json();
if (!isServerResponse(body)) {
throw new Error("missing or malformed body");
}
if (!("item" in body)) {
throw new Error("expected to receive an item");
}
const item = body.item;
if (!isMe(item)) {
throw new Error("expected to receive users 'me' object");
}
me = item;
}
if (!token && url.pathname !== "/login" && url.pathname !== "/login/__data.json") {
console.log("REDIRECTING", url.pathname);
const baseUrl = `${url.protocol}${url.host}`;
const loginUrl = new URL("login", baseUrl);
loginUrl.searchParams.set("to", url.pathname);
redirect(302, loginUrl);
} else {
console.log("no need to redirect");
}
return {
token,
me,
};
};