import { type ObjectRef, PothosSchemaError, type SchemaTypes } from '@pothos/core'; import { PrismaInterfaceRef, type PrismaRef } from '../interface-ref'; import { PrismaObjectRef } from '../object-ref'; import type { PrismaClient, PrismaDelegate, PrismaModelTypes } from '../types'; import { getDMMF } from './get-client'; export const refMap = new WeakMap>>(); export const findUniqueMap = new WeakMap< object, Map, ((args: unknown, ctx: {}) => unknown) | null> >(); export const includeForRefMap = new WeakMap< object, Map, Record | null> >(); export function getRefFromModel( name: string, builder: PothosSchemaTypes.SchemaBuilder, type: 'interface' | 'object' = 'object', ): PrismaRef { if (!refMap.has(builder)) { refMap.set(builder, new Map()); } const cache = refMap.get(builder)!; if (!cache.has(name)) { cache.set( name, type === 'object' ? new PrismaObjectRef(name, name) : new PrismaInterfaceRef(name, name), ); } return cache.get(name)! as never; } export function getRelation( name: string, builder: PothosSchemaTypes.SchemaBuilder, relation: string, ) { const fieldData = getFieldData(name, builder, relation); if (fieldData.kind !== 'object') { throw new PothosSchemaError( `Field ${relation} of model '${name}' is not a relation (${fieldData.kind})`, ); } return fieldData; } export function getFieldData( name: string, builder: PothosSchemaTypes.SchemaBuilder, fieldName: string, ) { const modelData = getModel(name, builder); const fieldData = modelData.fields.find((field) => field.name === fieldName); if (!fieldData) { throw new PothosSchemaError(`Field '${fieldName}' not found in model '${name}'`); } return fieldData; } export function getModel( name: string, builder: PothosSchemaTypes.SchemaBuilder, ) { const dmmf = getDMMF(builder); const modelData = Array.isArray(dmmf.models) ? dmmf.models.find((model) => model.name === name) : dmmf.models[name]; if (!modelData) { throw new PothosSchemaError(`Model '${name}' not found in DMMF`); } // Validate that the model data has the required fields for Prisma v7+ if (!modelData.uniqueIndexes) { throw new PothosSchemaError( `Model '${name}' is missing required datamodel information. ` + `This is likely because you're using Prisma v7+ without providing the generated datamodel. ` + 'Please follow the setup instructions at https://pothos-graphql.dev/docs/plugins/prisma#setup ' + 'to generate and configure the datamodel properly.', ); } return modelData; } export function getDelegateFromModel(client: PrismaClient, model: string) { const lowerCase = `${model.slice(0, 1).toLowerCase()}${model.slice(1)}`; const delegate = lowerCase in client ? (client as PrismaClient & Record)[lowerCase] : null; if (!delegate) { throw new PothosSchemaError(`Unable to find delegate for model ${model}`); } return delegate as PrismaDelegate; }