feat(api): add emergency profile read and write route

GET/PATCH /api/anamnesis/emergency, wrapped in apiHandler. The PATCH
validates a partial body with per-field length caps, builds the Prisma
data field-by-field from the parsed input (never a spread), narrows the
user from requireAuth rather than the body, encrypts the free text on
write, and audits the change. The GET decrypts fail-soft for the form
prefill. Registers the OpenAPI operations and schema. An integration
test reads the row back to prove the write lands.
This commit is contained in:
Marc-André Bombeck committed 2026-08-10 05:32:59 +02:00
1 parent 772da42348
commit 6770bf3b7f
7 files changed
+788 -3

No files matched your search

+59
View File
@@ -0,0 +1,59 @@
import { NextRequest } from "next/server";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import {
apiSuccess,
getClientIp,
returnAllZodIssues,
safeJson,
} from "@/lib/api-response";
import { auditLog } from "@/lib/auth/audit";
import { annotate } from "@/lib/logging/context";
import {
readEmergencyProfile,
writeEmergencyProfile,
} from "@/lib/profile/emergency-profile";
import { emergencyProfileUpdateSchema } from "@/lib/validations/emergency-profile";
export const GET = apiHandler(async () => {
const { user } = await requireAuth();
const payload = await readEmergencyProfile(user.id);
annotate({
action: { name: "anamnesis.emergency.get" },
meta: {
has_blood_type: payload.bloodType !== null,
has_contacts: payload.contacts !== null,
has_implants: payload.implants !== null,
},
});
return apiSuccess(payload);
});
export const PATCH = apiHandler(async (request: NextRequest) => {
const { user } = await requireAuth();
const { data: rawBody, error } = await safeJson(request, {
maxBytes: 16 * 1024,
});
if (error) return error;
const parsed = emergencyProfileUpdateSchema.safeParse(rawBody);
if (!parsed.success) return returnAllZodIssues(parsed.error, 422);
const payload = await writeEmergencyProfile(user.id, parsed.data);
await auditLog("anamnesis.emergency.update", {
userId: user.id,
ipAddress: getClientIp(request),
details: { fields: Object.keys(parsed.data).sort() },
});
annotate({
action: {
name: "anamnesis.emergency.update",
entity_type: "user_health_profile",
entity_id: user.id,
},
meta: { fields: Object.keys(parsed.data).sort() },
});
return apiSuccess(payload);
});
export const dynamic = "force-dynamic";