mirror of
https://github.com/bitbaum/petvity.git
synced 2026-12-04 12:07:39 +01:00
- 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>
42 lines
1.4 KiB
TypeScript
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;
|
|
}
|