Files
gutscheintracker/app/api/contacts/route.ts
T

48 lines
1.9 KiB
TypeScript

import { NextRequest, NextResponse } from "next/server";
import { getDb } from "@/lib/db";
import { validateContact } from "@/lib/contacts";
import { getViewer } from "@/lib/viewer";
import { resolveTarget, scopeWhere } from "@/lib/access";
export async function GET(req: NextRequest) {
const viewer = await getViewer();
if (!viewer) return NextResponse.json({ error: "unauthorized" }, { status: 401 });
const scopeParam = req.nextUrl.searchParams.get("scope");
const db = getDb();
const all = await db.contact.findMany({ where: scopeWhere(viewer), orderBy: { name: "asc" } });
if (!scopeParam) return NextResponse.json(all);
if (scopeParam === "household" && viewer.householdId !== null) {
return NextResponse.json(all.filter((c) => c.householdId === viewer.householdId));
}
if (scopeParam === "private") {
return NextResponse.json(all.filter((c) => c.householdId === null));
}
return NextResponse.json(all);
}
export async function POST(req: NextRequest) {
const viewer = await getViewer();
if (!viewer) return NextResponse.json({ error: "unauthorized" }, { status: 401 });
const body = await req.json().catch(() => ({}));
const target = resolveTarget(viewer, body.scope);
if (!target.ok) return NextResponse.json({ errors: ["scope"], message: target.error }, { status: 400 });
const input = {
name: String(body.name ?? ""),
email: body.email ? String(body.email) : null,
telegramChatId: body.telegramChatId ? String(body.telegramChatId) : null,
};
const errs = validateContact(input);
if (errs.length) return NextResponse.json({ errors: errs }, { status: 400 });
const db = getDb();
const created = await db.contact.create({
data: {
name: input.name.trim(),
email: input.email?.trim() || null,
telegramChatId: input.telegramChatId?.trim() || null,
ownerId: viewer.id,
householdId: target.householdId,
},
});
return NextResponse.json(created, { status: 201 });
}