feat(records): CRUD API + OpenAPI for allergies and family history

Add the `/api/allergies` and `/api/family-history` endpoints (list / create /
read / update / soft-delete), each wrapped in `apiHandler` with Zod
`safeParse` + `returnAllZodIssues`. `userId` is always narrowed from the
session/Bearer — never a body field — and the Prisma `data` is built
field-by-field (no mass assignment). Creates wrap in `withIdempotency`. The
free-text reaction/note are encrypted before write and decrypted fail-soft on
read via the server-authoritative DTOs.

Register the query-key factory entries and the OpenAPI route tables (new
`Records` tag); regenerate `docs/api/openapi.yaml`.
This commit is contained in:
Marc-André Bombeck committed 2026-06-28 16:03:05 +02:00
1 parent 3ded891641
commit 5052b2cc08
15 files changed
+1913

No files matched your search

+1
View File
@@ -75,6 +75,7 @@ const openApiBase: Pick<
{ name: "MeasurementReminders" },
{ name: "Labs" },
{ name: "Illness" },
{ name: "Records" },
{ name: "Admin" },
{ name: "Meta" },
],
+182
View File
@@ -0,0 +1,182 @@
/**
* OpenAPI route table for structured allergies (`/api/allergies`).
*
* Part of the OpenAPI route table; aggregated in `./index.ts`. The request
* bodies + queries reuse the runtime Zod schemas from
* `@/lib/validations/allergy` so the wire contract stays single-source.
* Response shapes are declared here to mirror the server-authoritative DTOs in
* `@/lib/records/dto.ts` (the routes serialise a decrypted `reaction` + `note`
* the input schemas don't carry; iOS renders the DTO, it never recomputes it).
*
* A structured AllergyIntolerance-style RECORD — patient-reported, never a
* clinical diagnosis. Owner-scoped; auth-gated.
*/
import type { ZodOpenApiObject } from "zod-openapi";
import { z } from "zod/v4";
import {
allergyCreateSchema,
allergyUpdateSchema,
allergyListQuerySchema,
allergyCategoryEnum,
allergyTypeEnum,
allergySeverityEnum,
allergyStatusEnum,
} from "@/lib/validations/allergy";
import { dataEnvelope, errorEnvelope, stdResponses } from "./shared";
allergyCreateSchema.meta({
id: "CreateAllergyRequest",
description:
"Record an allergy/intolerance. `substance` is the user-facing allergen name (the FHIR AllergyIntolerance `code.text` anchor — never a machine-guessed code). The free-text `reaction` + `note` are encrypted at rest. `onsetAt` is optional (unknown when omitted). Patient-reported.",
});
allergyUpdateSchema.meta({
id: "UpdateAllergyRequest",
description:
"Partial edit of an allergy; an omitted key leaves the column untouched. A `null` `severity`/`onsetAt`/`reaction`/`note` clears that field. Rejects unknown keys.",
});
allergyListQuerySchema.meta({
id: "ListAllergiesQuery",
description:
"Query params for the allergy list: optional `limit` (1–200, default 100) and `includeInactive` ('true' | 'false'); 'false' returns only ACTIVE records. Newest-first.",
});
const allergy = z
.object({
id: z.string(),
substance: z.string(),
category: allergyCategoryEnum,
type: allergyTypeEnum,
severity: allergySeverityEnum.nullable(),
status: allergyStatusEnum,
onsetAt: z.string().nullable(),
reaction: z.string().nullable(),
note: z.string().nullable(),
createdAt: z.string(),
updatedAt: z.string(),
})
.meta({
id: "Allergy",
description:
"A stored allergy/intolerance record. `reaction` + `note` are the decrypted free-text (or null on a key-rotation gap — fail-soft, never 500). `severity`/`onsetAt` are null when not assessed/known.",
});
const allergyNotFound = {
"404": {
description: "Allergy not found (or owned by another user).",
content: { "application/json": { schema: errorEnvelope } },
},
} as const;
export const allergyPaths: NonNullable<ZodOpenApiObject["paths"]> = {
"/api/allergies": {
get: {
tags: ["Records"],
summary: "List allergies (v1.25)",
description:
"Returns the caller's live (non-deleted) allergy/intolerance records, newest-first. `includeInactive=false` returns only ACTIVE records.",
requestParams: { query: allergyListQuerySchema },
responses: {
"200": {
description: "The caller's allergy records.",
content: {
"application/json": {
schema: dataEnvelope(z.array(allergy), "ListAllergiesEnvelope"),
},
},
},
...stdResponses,
},
},
post: {
tags: ["Records"],
summary: "Record an allergy (v1.25)",
description:
"Creates one allergy/intolerance record for the caller. The free-text reaction + note are AES-256-GCM encrypted before write. Audits as `allergy.create`.",
requestBody: {
required: true,
content: { "application/json": { schema: allergyCreateSchema } },
},
responses: {
"201": {
description: "Allergy created.",
content: {
"application/json": {
schema: dataEnvelope(allergy, "CreateAllergyEnvelope"),
},
},
},
...stdResponses,
},
},
},
"/api/allergies/{id}": {
get: {
tags: ["Records"],
summary: "Read a single allergy (v1.25)",
description:
"Returns the record including its decrypted `reaction` + `note`. Owner-scoped; a cross-user or tombstoned id 404s.",
requestParams: { path: z.object({ id: z.string() }) },
responses: {
"200": {
description: "The allergy record.",
content: {
"application/json": {
schema: dataEnvelope(allergy, "GetAllergyEnvelope"),
},
},
},
...allergyNotFound,
...stdResponses,
},
},
patch: {
tags: ["Records"],
summary: "Edit an allergy (v1.25)",
description:
"Partial edit; omitted fields are left untouched. Audits as `allergy.update`. Owner-scoped.",
requestParams: { path: z.object({ id: z.string() }) },
requestBody: {
required: true,
content: { "application/json": { schema: allergyUpdateSchema } },
},
responses: {
"200": {
description: "Allergy updated.",
content: {
"application/json": {
schema: dataEnvelope(allergy, "UpdateAllergyEnvelope"),
},
},
},
...allergyNotFound,
...stdResponses,
},
},
delete: {
tags: ["Records"],
summary: "Soft-delete an allergy (v1.25)",
description:
"Stamps `deletedAt` (tombstone). Idempotent — a re-delete is a no-op. Returns the `{ deleted: true }` envelope. Audits as `allergy.delete`. Owner-scoped.",
requestParams: { path: z.object({ id: z.string() }) },
responses: {
"200": {
description: "Soft-deleted.",
content: {
"application/json": {
schema: dataEnvelope(
z.object({ deleted: z.boolean() }),
"DeleteAllergyEnvelope",
),
},
},
},
...allergyNotFound,
...stdResponses,
},
},
},
};
+191
View File
@@ -0,0 +1,191 @@
/**
* OpenAPI route table for structured family history (`/api/family-history`).
*
* Part of the OpenAPI route table; aggregated in `./index.ts`. The request
* bodies + queries reuse the runtime Zod schemas from
* `@/lib/validations/family-history` so the wire contract stays single-source.
* Response shapes mirror the server-authoritative DTOs in
* `@/lib/records/dto.ts` (the routes serialise a decrypted `note` the input
* schemas don't carry; iOS renders the DTO, it never recomputes it).
*
* A structured FamilyMemberHistory-style RECORD — patient-reported, never a
* clinical diagnosis. Owner-scoped; auth-gated.
*/
import type { ZodOpenApiObject } from "zod-openapi";
import { z } from "zod/v4";
import {
familyHistoryCreateSchema,
familyHistoryUpdateSchema,
familyHistoryListQuerySchema,
familyRelationshipEnum,
} from "@/lib/validations/family-history";
import { dataEnvelope, errorEnvelope, stdResponses } from "./shared";
familyHistoryCreateSchema.meta({
id: "CreateFamilyHistoryRequest",
description:
"Record one condition for one relative (a FHIR FamilyMemberHistory with a single condition). `condition` is the user-facing label (the `condition.code.text` anchor — never a machine-guessed code); `ageAtOnset` is the relative's age (years) when it began. The free-text `note` is encrypted at rest. Patient-reported.",
});
familyHistoryUpdateSchema.meta({
id: "UpdateFamilyHistoryRequest",
description:
"Partial edit of a family-history entry; an omitted key leaves the column untouched. A `null` `ageAtOnset`/`note` clears that field. Rejects unknown keys.",
});
familyHistoryListQuerySchema.meta({
id: "ListFamilyHistoryQuery",
description:
"Query params for the family-history list: optional `limit` (1–200, default 100). Newest-first.",
});
const familyHistoryEntry = z
.object({
id: z.string(),
relationship: familyRelationshipEnum,
condition: z.string(),
ageAtOnset: z.number().int().nullable(),
note: z.string().nullable(),
createdAt: z.string(),
updatedAt: z.string(),
})
.meta({
id: "FamilyHistoryEntry",
description:
"A stored family-history entry: one condition for one relative. `note` is the decrypted free-text (or null on a key-rotation gap — fail-soft, never 500). `ageAtOnset` is null when unknown.",
});
const entryNotFound = {
"404": {
description: "Family history entry not found (or owned by another user).",
content: { "application/json": { schema: errorEnvelope } },
},
} as const;
export const familyHistoryPaths: NonNullable<ZodOpenApiObject["paths"]> = {
"/api/family-history": {
get: {
tags: ["Records"],
summary: "List family history (v1.25)",
description:
"Returns the caller's live (non-deleted) family-history entries, newest-first.",
requestParams: { query: familyHistoryListQuerySchema },
responses: {
"200": {
description: "The caller's family-history entries.",
content: {
"application/json": {
schema: dataEnvelope(
z.array(familyHistoryEntry),
"ListFamilyHistoryEnvelope",
),
},
},
},
...stdResponses,
},
},
post: {
tags: ["Records"],
summary: "Record a family-history entry (v1.25)",
description:
"Creates one condition-by-relative record for the caller. The free-text note is AES-256-GCM encrypted before write. Audits as `family-history.create`.",
requestBody: {
required: true,
content: {
"application/json": { schema: familyHistoryCreateSchema },
},
},
responses: {
"201": {
description: "Entry created.",
content: {
"application/json": {
schema: dataEnvelope(
familyHistoryEntry,
"CreateFamilyHistoryEnvelope",
),
},
},
},
...stdResponses,
},
},
},
"/api/family-history/{id}": {
get: {
tags: ["Records"],
summary: "Read a single family-history entry (v1.25)",
description:
"Returns the entry including its decrypted `note`. Owner-scoped; a cross-user or tombstoned id 404s.",
requestParams: { path: z.object({ id: z.string() }) },
responses: {
"200": {
description: "The family-history entry.",
content: {
"application/json": {
schema: dataEnvelope(
familyHistoryEntry,
"GetFamilyHistoryEnvelope",
),
},
},
},
...entryNotFound,
...stdResponses,
},
},
patch: {
tags: ["Records"],
summary: "Edit a family-history entry (v1.25)",
description:
"Partial edit; omitted fields are left untouched. Audits as `family-history.update`. Owner-scoped.",
requestParams: { path: z.object({ id: z.string() }) },
requestBody: {
required: true,
content: {
"application/json": { schema: familyHistoryUpdateSchema },
},
},
responses: {
"200": {
description: "Entry updated.",
content: {
"application/json": {
schema: dataEnvelope(
familyHistoryEntry,
"UpdateFamilyHistoryEnvelope",
),
},
},
},
...entryNotFound,
...stdResponses,
},
},
delete: {
tags: ["Records"],
summary: "Soft-delete a family-history entry (v1.25)",
description:
"Stamps `deletedAt` (tombstone). Idempotent — a re-delete is a no-op. Returns the `{ deleted: true }` envelope. Audits as `family-history.delete`. Owner-scoped.",
requestParams: { path: z.object({ id: z.string() }) },
responses: {
"200": {
description: "Soft-deleted.",
content: {
"application/json": {
schema: dataEnvelope(
z.object({ deleted: z.boolean() }),
"DeleteFamilyHistoryEnvelope",
),
},
},
},
...entryNotFound,
...stdResponses,
},
},
},
};
+4
View File
@@ -22,6 +22,7 @@
import type { ZodOpenApiObject } from "zod-openapi";
import { adminDiagnosticPaths, adminInvitePaths } from "./admin";
import { allergyPaths } from "./allergies";
import { authPaths } from "./auth";
import {
coachFeedbackPaths,
@@ -35,6 +36,7 @@ import { cyclePaths } from "./cycle";
import { biomarkerPaths } from "./biomarkers";
import { devicePaths } from "./devices";
import { exportPaths } from "./export";
import { familyHistoryPaths } from "./family-history";
import { healthRecordPaths } from "./health-record";
import { illnessPaths } from "./illness";
import { importPaths } from "./import";
@@ -83,6 +85,8 @@ export const openApiPaths: NonNullable<ZodOpenApiObject["paths"]> = {
...ocrPaths,
...biomarkerPaths,
...illnessPaths,
...allergyPaths,
...familyHistoryPaths,
...onboardingPaths,
};