Files
petvity/lib/api/ownership.ts
T
g-butandClaude Sonnet 4.6 63c67cdb9c refactor(api): enforce SSOT for enums + extract ownership helpers
- Derive Zod enum validation from schema pgEnum.enumValues instead of
  hardcoded arrays (SSOT: schema is the single source of truth)
- Extract verifyOwnership into lib/api/ownership.ts with one JOIN query
  per entity — eliminates N+1 two-query pattern and removes 3× duplication
- Fix medications POST missing status field (form sent it, API silently
  dropped it, defaulting all new meds to "active" regardless of input)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-22 13:43:53 +02:00

42 lines
1.4 KiB
TypeScript

/**
* Ownership verification helpers — single JOIN query per entity.
* Each function returns the row only when it exists AND the pet belongs to userId.
*/
import { and, eq } from "drizzle-orm";
import { getInstance } from "@/lib/db";
import { healthRecords, medications, pets, vaccinations } from "@/lib/db/schema";
export async function getHealthRecordForOwner(recordId: string, userId: string) {
const db = getInstance();
const [row] = await db
.select({ record: healthRecords })
.from(healthRecords)
.innerJoin(pets, and(eq(pets.id, healthRecords.petId), eq(pets.ownerId, userId)))
.where(eq(healthRecords.id, recordId))
.limit(1);
return row?.record ?? null;
}
export async function getVaccinationForOwner(vaccinationId: string, userId: string) {
const db = getInstance();
const [row] = await db
.select({ record: vaccinations })
.from(vaccinations)
.innerJoin(pets, and(eq(pets.id, vaccinations.petId), eq(pets.ownerId, userId)))
.where(eq(vaccinations.id, vaccinationId))
.limit(1);
return row?.record ?? null;
}
export async function getMedicationForOwner(medicationId: string, userId: string) {
const db = getInstance();
const [row] = await db
.select({ record: medications })
.from(medications)
.innerJoin(pets, and(eq(pets.id, medications.petId), eq(pets.ownerId, userId)))
.where(eq(medications.id, medicationId))
.limit(1);
return row?.record ?? null;
}