What's the best practice for selecting an item only if a nullable field is not-null?

In this case, I have a type Patient which has a nullable field called stripeCustomerId. I create the patient earlier, and when I collect customer information, I add to it.

Although, sometimes, I want to getPatient but I want it to throw an error if stripeCustomerId or another similar field is missing. I'd also like to handle errors in my getPatient function, so I don't have to handle errors everytime I call it.

I created this, but I'm wondering if there's a better way. I'm still a novice.
"use server";

import { db } from "@/drizzle/db";
import { type Patient, patients } from "@/drizzle/schema/patients";
import { eq } from "drizzle-orm";
import { DrizzleError } from "drizzle-orm";

interface GetPatientProps {
    id: NonNullable<Patient["id"]>;
    requireFields?: (keyof Patient)[];
}

export const getPatient = async ({
    id,
    requireFields = [],
}: GetPatientProps) => {
    try {
        const patient = await db
            .select()
            .from(patients)
            .where(eq(patients.id, id))
            .limit(1);

        const foundPatient = patient[0];

        if (!foundPatient) {
            throw new Error(`Patient with id ${id} not found`);
        }

        if (requireFields.length > 0) {
            const missingFields = [];
            for (const field of requireFields) {
                if (foundPatient[field] === undefined) {
                    missingFields.push(field);
                }
            }

            if (missingFields.length > 0) {
                throw new Error(`Required fields missing: ${missingFields.join(", ")}`);
            }
        }

        return foundPatient;
    } catch (error) {
        if (error instanceof DrizzleError) {
            throw new Error(`Drizzle error: ${error.message}`);
        }
        throw error;
    }
};
Was this page helpful?