2026-03-23 20:58:42 +02:00
|
|
|
import { mustGetQuery } from "@rocicorp/zero";
|
|
|
|
|
import { handleQueryRequest } from "@rocicorp/zero/server";
|
|
|
|
|
import { NextResponse } from "next/server";
|
2026-03-24 16:06:20 +02:00
|
|
|
import type { Context } from "@/types/zero";
|
2026-03-23 20:58:42 +02:00
|
|
|
import { queries } from "@/zero/queries";
|
|
|
|
|
import { schema } from "@/zero/schema";
|
|
|
|
|
|
2026-03-24 16:06:20 +02:00
|
|
|
const backendURL = process.env.NEXT_PUBLIC_FASTAPI_BACKEND_URL || "http://localhost:8000";
|
|
|
|
|
|
|
|
|
|
async function authenticateRequest(
|
|
|
|
|
request: Request
|
|
|
|
|
): Promise<{ ctx: Context; error?: never } | { ctx?: never; error: NextResponse }> {
|
|
|
|
|
const authHeader = request.headers.get("Authorization");
|
|
|
|
|
if (!authHeader?.startsWith("Bearer ")) {
|
2026-03-24 16:59:42 +02:00
|
|
|
return { ctx: undefined };
|
2026-03-24 16:06:20 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
const res = await fetch(`${backendURL}/users/me`, {
|
|
|
|
|
headers: { Authorization: authHeader },
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
if (!res.ok) {
|
|
|
|
|
return { error: NextResponse.json({ error: "Unauthorized" }, { status: 401 }) };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const user = await res.json();
|
|
|
|
|
return { ctx: { userId: String(user.id) } };
|
|
|
|
|
} catch {
|
|
|
|
|
return { error: NextResponse.json({ error: "Auth service unavailable" }, { status: 503 }) };
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-23 20:58:42 +02:00
|
|
|
export async function POST(request: Request) {
|
2026-03-24 16:06:20 +02:00
|
|
|
const auth = await authenticateRequest(request);
|
|
|
|
|
if (auth.error) {
|
|
|
|
|
return auth.error;
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-23 20:58:42 +02:00
|
|
|
const result = await handleQueryRequest(
|
|
|
|
|
(name, args) => {
|
|
|
|
|
const query = mustGetQuery(queries, name);
|
2026-03-24 16:06:20 +02:00
|
|
|
return query.fn({ args, ctx: auth.ctx });
|
2026-03-23 20:58:42 +02:00
|
|
|
},
|
|
|
|
|
schema,
|
2026-03-24 16:06:20 +02:00
|
|
|
request
|
2026-03-23 20:58:42 +02:00
|
|
|
);
|
|
|
|
|
|
|
|
|
|
return NextResponse.json(result);
|
|
|
|
|
}
|