2026-03-04 18:07:18 +01:00
|
|
|
import type { YogaInitialContext } from "graphql-yoga";
|
2026-03-04 20:31:18 +01:00
|
|
|
import type { FastifyRequest, FastifyReply } from "fastify";
|
2026-03-04 18:42:58 +01:00
|
|
|
import type { Context } from "./builder";
|
|
|
|
|
import { getSession } from "../lib/auth";
|
|
|
|
|
import { db } from "../db/connection";
|
|
|
|
|
import { redis } from "../lib/auth";
|
2026-03-04 18:07:18 +01:00
|
|
|
|
2026-03-04 20:31:18 +01:00
|
|
|
type ServerContext = {
|
|
|
|
|
req: FastifyRequest;
|
|
|
|
|
reply: FastifyReply;
|
|
|
|
|
db: typeof db;
|
|
|
|
|
redis: typeof redis;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export async function buildContext(ctx: YogaInitialContext & ServerContext): Promise<Context> {
|
2026-03-04 18:07:18 +01:00
|
|
|
const request = ctx.request;
|
|
|
|
|
const cookieHeader = request.headers.get("cookie") || "";
|
|
|
|
|
|
|
|
|
|
// Parse session_token from cookies
|
|
|
|
|
const cookies = Object.fromEntries(
|
|
|
|
|
cookieHeader.split(";").map((c) => {
|
|
|
|
|
const [k, ...v] = c.trim().split("=");
|
|
|
|
|
return [k.trim(), v.join("=")];
|
|
|
|
|
}),
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
const token = cookies["session_token"];
|
|
|
|
|
const currentUser = token ? await getSession(token) : null;
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
db: ctx.db || db,
|
|
|
|
|
redis: ctx.redis || redis,
|
|
|
|
|
currentUser,
|
|
|
|
|
request,
|
|
|
|
|
reply: ctx.reply,
|
|
|
|
|
};
|
|
|
|
|
}
|