import { createContextCache, type InterfaceRef, isThenable, type MaybePromise, type ObjectRef, PothosSchemaError, type SchemaTypes, } from '@pothos/core'; import { fieldKey, forExecution, Plan, setRowMappings } from '@pothos/selection-mapper'; import type { GraphQLResolveInfo } from 'graphql'; import type { SelectionMap } from './types.js'; import { type PrismaNode, type PrismaPlayedPlan, prismaAdapter } from './util/adapter.js'; import { getDelegateFromModel, getModel } from './util/datamodel.js'; import { InternalError } from './util/errors.js'; import { getClient } from './util/get-client.js'; import type { FieldMap } from './util/relation-map.js'; interface ResolvablePromise { promise: Promise; resolve: (value: T) => void; reject: (err: unknown) => void; } export class ModelLoader { context: object; builder: PothosSchemaTypes.SchemaBuilder; findUnique: (model: Record, ctx: {}) => MaybePromise; modelName: string; // One parent-row plan per `fieldKey` per execution, played where it is made since it is never // played behind another selection; a promise while a select beneath the field is async. Kept // per execution (see `forExecution`), so neither an operation sharing the context nor a later // subscription event reloads with another's plan. queryCache = new WeakMap>>(); // Each batch owns the node it accumulates into, so nothing a cached play holds is changed by a // row joining the batch. staged = new Set<{ root: PrismaNode; models: Map | null>>; }>(); tick = Promise.resolve(); constructor( context: object, builder: PothosSchemaTypes.SchemaBuilder, modelName: string, findUnique: (model: Record, ctx: {}) => MaybePromise, ) { this.context = context; this.builder = builder; this.findUnique = findUnique; this.modelName = modelName; } static forRef( ref: InterfaceRef | ObjectRef, modelName: string, findUnique: | ((model: Record, ctx: {}) => MaybePromise) | null | undefined, builder: PothosSchemaTypes.SchemaBuilder, ) { return createContextCache( (model) => new ModelLoader( model, builder as never, modelName, findUnique === null ? () => { throw new InternalError(`Missing findUnique for ${ref.name}`); } : (findUnique ?? ModelLoader.getFindUnique(ModelLoader.getDefaultFindBy(ref, modelName, builder))), ), ); } static getFindUnique( findBy: | string | { name: string | null; fields: string[]; }, ): (model: Record) => {} { if (typeof findBy === 'string') { return (parent) => ({ [findBy]: parent[findBy] }); } const { fields, name: primaryKeyName } = findBy; return (parent) => { const primaryKey: Record = {}; for (const key of fields) { primaryKey[key] = parent[key]; } return { [primaryKeyName ?? fields.join('_')]: primaryKey }; }; } static getDefaultFindBy( ref: InterfaceRef | ObjectRef, modelName: string, builder: PothosSchemaTypes.SchemaBuilder, ) { const model = getModel(modelName, builder); const idField = model.fields.find((field) => field.isId); const uniqueField = model.fields.find((field) => field.isRequired && field.isUnique); const uniqueIndex = model.uniqueIndexes.find((idx) => idx.fields.every((field) => model.fields.find((f) => f.name === field)?.isRequired), ); let findBy: | string | { name: string | null; fields: string[]; } | undefined; if (model.primaryKey) { findBy = model.primaryKey; } else if (idField) { findBy = idField.name; } else if (uniqueField) { findBy = uniqueField.name; } else if (uniqueIndex) { findBy = uniqueIndex; } if (!findBy) { throw new PothosSchemaError(`Missing findUnique for ${ref.name}`); } return findBy; } static getDefaultIDSelection( ref: InterfaceRef | ObjectRef, modelName: string, builder: PothosSchemaTypes.SchemaBuilder, ): Record { const findBy = ModelLoader.getDefaultFindBy(ref, modelName, builder); if (typeof findBy === 'string') { return { [findBy]: true }; } const result: Record = {}; for (const field of findBy.fields) { result[field] = true; } return result; } static getCursorSelection( ref: InterfaceRef | ObjectRef, modelName: string, cursor: string, builder: PothosSchemaTypes.SchemaBuilder, ): Record { const model = getModel(modelName, builder); const field = model.fields.find((field) => field.name === cursor); if (field) { return { [field.name]: true }; } const index = [model.primaryKey, ...model.uniqueIndexes] .filter(Boolean) .find((idx) => (idx!.name ?? idx!.fields.join('_')) === cursor); if (!index) { throw new PothosSchemaError(`Can't find "${cursor}" field or index for ${ref.name}`); } const selection: Record = {}; for (const column of index.fields) { selection[column] = true; } return selection; } static getFindUniqueForField( ref: InterfaceRef | ObjectRef, modelName: string, fieldName: string, builder: PothosSchemaTypes.SchemaBuilder, ): (model: Record) => {} { const model = getModel(modelName, builder); const uniqueIndex = model.uniqueIndexes.find( (idx) => (idx.name ?? idx.fields.join('_')) === fieldName, ); let findBy: | string | { name: string | null; fields: string[]; } | undefined; if (model.fields.some((field) => field.name === fieldName)) { findBy = fieldName; } else if ( model.primaryKey && (model.primaryKey?.name ?? model.primaryKey?.fields.join('_')) === fieldName ) { findBy = model.primaryKey; } else if (uniqueIndex) { findBy = uniqueIndex; } if (!findBy) { throw new PothosSchemaError(`Unable to find field or index for ${fieldName} of ${ref.name}`); } return ModelLoader.getFindUnique(findBy); } getSelection(info: GraphQLResolveInfo) { const plans = forExecution(this.queryCache, info); const key = fieldKey(info.parentType.name, info); let plan = plans.get(key); if (!plan) { plan = Plan.forParentRow(prismaAdapter, { context: this.context, info, skipDeferredFragments: this.builder.options.prisma.skipDeferredFragments ?? true, }); plans.set(key, plan); } return plan; } /** * `model` reloaded with the selection of the field `info` resolves. A synchronous selection * stages synchronously, so every row resolved in a tick joins the same batch; only a selection * with an async select beneath the field waits for it. */ loadSelection(info: GraphQLResolveInfo, model: object): Promise | null> { const selection = this.getSelection(info); return isThenable(selection) ? selection.then((settled) => this.loadWith(settled, info, model)) : this.loadWith(selection, info, model); } private loadWith(played: PrismaPlayedPlan, info: GraphQLResolveInfo, model: object) { return this.stageQuery(played, model).then((result) => { if (result) { const mapping = played.mappings[`${info.parentType.name}@${info.path.key}`]; if (mapping) { // This plan loaded `result` alone, so its mappings are the row's, not the field's: a // sibling row of the same list that the planned query did load must keep answering // from the plan. setRowMappings(this.context, info, mapping.nested); } } return result; }); } stageQuery(played: Pick, model: object) { for (const entry of this.staged) { // Node to node: the batch takes the field's play whole, never through a query. if (prismaAdapter.canMergeNode(entry.root, played.root)) { prismaAdapter.mergeNode(entry.root, played.root); if (!entry.models.has(model)) { entry.models.set(model, createResolvablePromise | null>()); } return entry.models.get(model)!.promise; } } return this.initLoad(played, model); } initLoad(played: Pick, initialModel: {}) { const delegate = getDelegateFromModel( getClient(this.builder, this.context as never), this.modelName, ); const models = new Map | null>>(); const promise = createResolvablePromise | null>(); models.set(initialModel, promise); const root = prismaAdapter.createNode(played.root.model); prismaAdapter.mergeNode(root, played.root); const entry = { models, root, }; this.staged.add(entry); const nextTick = createResolvablePromise(); this.tick.then(() => { this.staged.delete(entry); const rejectBatch = (error: unknown) => { for (const { reject } of entry.models.values()) { reject(error); } }; const load = (where: {}) => delegate.findUniqueOrThrow ? delegate.findUniqueOrThrow({ ...prismaAdapter.toQuery(entry.root), where: { ...where }, } as never) : delegate.findUnique({ rejectOnNotFound: true, ...prismaAdapter.toQuery(entry.root), where: { ...where }, } as never); try { for (const [model, { resolve, reject }] of entry.models) { const where = this.findUnique(model as Record, this.context); if (isThenable(where)) { where.then((settled) => { try { load(settled as {}).then(resolve as () => {}, reject); } catch (error) { reject(error); } }, reject); } else { load(where as {}).then(resolve as () => {}, reject); } } } catch (error) { rejectBatch(error); } }); setTimeout(() => nextTick.resolve(), 0); this.tick = nextTick.promise; return promise.promise; } } /** Matches `ScopeAuthParentLoader` in @pothos/plugin-scope-auth, which this plugin can't import. */ type ScopeAuthParentLoader = ( parent: unknown, context: object, info: GraphQLResolveInfo, ) => MaybePromise; /** * The parent scope-auth's checks see for a type: the row when it has every top-level key of the * type's selection, otherwise the row reloaded with it. `scalars` are the columns of include mode, * which loads every scalar. */ export function typeParentLoader( loaders: (context: object) => ModelLoader, fieldMap: FieldMap, selection: SelectionMap, scalars: readonly string[], ): ScopeAuthParentLoader { const root = prismaAdapter.createNode(fieldMap); prismaAdapter.mergeQuery(root, selection); const keys = [ ...(root.columns ?? scalars), ...root.relations.keys(), ...(root.computed.size > 0 ? ['_count'] : []), ]; // By root field path, which graphql makes for each root field of each execution, then row. const loads = new WeakMap>>(); const reload = (row: Record, context: object, info: GraphQLResolveInfo) => { let path = info.path; while (path.prev) { path = path.prev; } let rows = loads.get(path); if (!rows) { rows = new WeakMap(); loads.set(path, rows); } let load = rows.get(row); if (!load) { load = new Promise | null>((resolve) => { resolve(loaders(context).stageQuery({ root }, row)); }) .then((loaded) => { // Loaded values win for the selection's keys. The row's other keys are kept. const merged = { ...row }; for (const key of keys) { merged[key] = loaded![key]; } return merged; }) .catch((error: unknown) => { // Clients see only a generic message. throw new Error('Unexpected error.', { cause: error }); }); rows.set(row, load); } return load; }; return (parent, context, info) => { const row = parent as Record; for (let i = 0; i < keys.length; i += 1) { if (row[keys[i]] === undefined) { return reload(row, context, info); } } return row; }; } function createResolvablePromise(): ResolvablePromise { let resolveFn!: (value: T) => void; let rejectFn!: (reason?: unknown) => void; const promise = new Promise((resolve, reject) => { resolveFn = resolve; rejectFn = reject; }); return { promise, resolve: resolveFn, reject: rejectFn }; }