import { isError } from '@prisma/sdk' ; import type { Action } from '../getPrismaClient' ; export type RejectOnNotFound = boolean | ( ( error : Error ) => Error ) | undefined ; export type InstanceRejectOnNotFound = RejectOnNotFound | Record < string , RejectOnNotFound > | Record < string , Record < string , RejectOnNotFound > > ; export class NotFoundError extends Error { constructor ( message ) { super ( message ) ; this . name = 'NotFoundError' ; } } param action param args param instance returns { RejectOnNotFound } export function getRejectOnNotFound ( action , modelName , args ? , clientInstance ? ) { let rejectOnNotFound ; if ( args && typeof args === 'object' && 'rejectOnNotFound' in args && args [ 'rejectOnNotFound' ] !== undefined ) { rejectOnNotFound = args [ 'rejectOnNotFound' ] ; delete args [ 'rejectOnNotFound' ] ; } else if ( typeof clientInstance === 'boolean' ) { rejectOnNotFound = clientInstance ; } else if ( clientInstance && typeof clientInstance === 'object' && action in clientInstance ) { const rejectPerOperation = clientInstance [ action ] ; if ( rejectPerOperation && typeof rejectPerOperation === 'object' ) { if ( modelName in rejectPerOperation ) { return rejectPerOperation [ modelName ] ; } return undefined ; } rejectOnNotFound = getRejectOnNotFound ( action , modelName , args , rejectPerOperation ) ; } else if ( typeof clientInstance === 'function' ) { rejectOnNotFound = clientInstance ; } else { rejectOnNotFound = false ; } return rejectOnNotFound ; } const REGEX = /(findUnique|findFirst)/ ; param data param clientMethod param typeName param rejectOnNotFound export function throwIfNotFound ( data , clientMethod , typeName , rejectOnNotFound ? ) { if ( rejectOnNotFound && ! data && REGEX . exec ( clientMethod ) ) { if ( typeof rejectOnNotFound === 'boolean' && rejectOnNotFound ) { throw new NotFoundError ( `No ${ typeName } found` ) ; } else if ( typeof rejectOnNotFound === 'function' ) { throw rejectOnNotFound ( new NotFoundError ( `No ${ typeName } found` ) ) ; } else if ( isError ( rejectOnNotFound ) ) { throw rejectOnNotFound ; } throw new NotFoundError ( `No ${ typeName } found` ) ; } }