import './global-types.js'; import './field-builder.js'; import './schema-builder.js'; import SchemaBuilder, { BasePlugin, completeValue, type PothosOutputFieldConfig, PothosSchemaError, type PothosTypeConfig, type SchemaTypes, unwrapOutputFieldType, } from '@pothos/core'; import { getLoaderMapping, mappingParentTypes, setRowMappings } from '@pothos/selection-mapper'; import type { TableRelationalConfig } from 'drizzle-orm'; import type { GraphQLFieldResolver, GraphQLResolveInfo } from 'graphql'; import type { ModelLoader } from './model-loader.js'; import type { PathInfo } from './types.js'; import { setPlannedPosition } from './utils/path-info.js'; export { drizzleConnectionHelpers } from './connection-helpers.js'; export { DrizzleObjectFieldBuilder } from './drizzle-field-builder.js'; export type { DrizzleNodeRef } from './node-ref.js'; export type { drizzleTableKey } from './object-ref.js'; export * from './types.js'; export { drizzleTableName } from './types.js'; export { drizzleClientCache, getSchemaConfig, type PothosDrizzleSchemaConfig, } from './utils/config.js'; export { type DrizzleQueryFromInfoResult, type QueryFromInfoOptions, type QueryFromInfoResult, type QueryFromInfoReturn, queryFromInfo, } from './utils/map-query.js'; export type { SelectionMap } from './utils/selections.js'; const pluginName = 'drizzle'; export default pluginName; export class PothosDrizzlePlugin extends BasePlugin { override onTypeConfig(typeConfig: PothosTypeConfig): PothosTypeConfig { if (typeConfig.kind !== 'Object' && typeConfig.kind !== 'Interface') { return typeConfig; } let model = typeConfig.extensions?.pothosDrizzleModel as string | undefined; let table = typeConfig.extensions?.pothosDrizzleTable as TableRelationalConfig | undefined; for (const iface of typeConfig.interfaces) { const interfaceConfig = this.buildCache.getTypeConfig(iface, 'Interface'); const interfaceModel = interfaceConfig.extensions?.pothosDrizzleModel as string | undefined; if (interfaceModel) { if (model && model !== interfaceModel) { throw new PothosSchemaError( `DrizzleObjects must be based on the same drizzle table as any DrizzleInterfaces they extend. ${typeConfig.name} uses ${model} and ${iface.name} uses ${interfaceModel}`, ); } model = interfaceModel; // A plain object type implementing a drizzle interface is walked with the interface's // table, so fragments on it plan the relations it inherits. table ??= interfaceConfig.extensions?.pothosDrizzleTable as | TableRelationalConfig | undefined; } } return { ...typeConfig, extensions: { ...typeConfig.extensions, pothosDrizzleModel: model, pothosDrizzleTable: table, }, }; } override onOutputFieldConfig( fieldConfig: PothosOutputFieldConfig, ): PothosOutputFieldConfig | null { if ( fieldConfig.kind === 'DrizzleObject' && fieldConfig.pothosOptions.select && !fieldConfig.extensions?.pothosDrizzleSelect ) { const { select } = fieldConfig.pothosOptions; return { ...fieldConfig, extensions: { ...fieldConfig.extensions, pothosDrizzleSelect: typeof select === 'function' ? ( args: {}, ctx: Types['Context'], nestedQuery: (query: unknown, path?: string[]) => never, _resolveSelection: unknown, pathInfo: PathInfo, ) => { // A field's select also reads its metadata from the nested selection function. // Forwarded lazily: reading the path ties the walk beneath the field to this // invocation, so a select that never reads it keeps that walk shared. const nestedQueryWithPath = Object.defineProperties(nestedQuery, { path: { get: () => pathInfo.path, enumerable: true }, segments: { get: () => pathInfo.segments, enumerable: true }, }); return completeValue( (select as (args: unknown, ctx: unknown, nestedQuery: unknown) => {} | null)( args, ctx, nestedQueryWithPath, ), wrapSelect, ); } : { columns: {}, ...select, }, }, }; } return { ...fieldConfig, }; } override wrapResolve( resolver: GraphQLFieldResolver, fieldConfig: PothosOutputFieldConfig, ): GraphQLFieldResolver { if (fieldConfig.kind !== 'DrizzleObject' || !fieldConfig.extensions?.pothosDrizzleSelect) { return resolver; } const parentConfig = this.buildCache.getTypeConfig(fieldConfig.parentType); // A field can declare how to tell whether its data is already on the parent row. When the // row was not loaded from the planned query (a resolver returned a row it fetched itself), // the mapping alone is not proof, and the field falls back to the model loader. const loadedCheck = fieldConfig.extensions?.pothosDrizzleLoaded as | ((value: unknown, info: GraphQLResolveInfo, context: object) => boolean) | undefined; const parentTypes = mappingParentTypes(this.buildCache, fieldConfig, 'pothosDrizzleModel'); const modelLoader = parentConfig.extensions?.pothosDrizzleLoader as ReturnType< typeof ModelLoader.forModel >; if (!modelLoader) { throw new Error(`ModelLoader not found for type ${parentConfig.name}`); } const gated: GraphQLFieldResolver = ( parent, args, context, info, ) => { // Asked of the row: a mapping recorded for this row wins over the plan's, which answers // for the rows the planned query loaded. let mapping = getLoaderMapping(context, info, info.parentType.name, parent); if (!mapping) { for (const parentType of parentTypes) { mapping = getLoaderMapping(context, info, parentType, parent); if (mapping) { break; } } } if ((!loadedCheck || loadedCheck(parent, info, context)) && mapping) { // The resolver reads the position it was planned at by `info.path`, whichever same-model // type the mapping was found under. The fields beneath answer from this row's plan: a // sibling row of the same list may have been loaded by another plan. if (mapping.position) { setPlannedPosition(info.path, mapping.position); } setRowMappings(context, info, mapping.nested); return resolver(parent, args, context, info); } return modelLoader(context) .loadSelection(info, parent as object) .then((result) => resolver(result, args, context, info)); }; // An exposed scalar or enum reads only its column, and has no fields beneath it, so a row // holding a value for the column resolves it as it is. const column = fieldConfig.extensions?.pothosDrizzleExposedColumn as string | false | undefined; if (!column) { return gated; } const returnKind = this.buildCache.getTypeConfig(unwrapOutputFieldType(fieldConfig.type)).kind; if (returnKind !== 'Scalar' && returnKind !== 'Enum') { return gated; } return (parent, args, context, info) => { const row = parent as Record; if (Object.hasOwn(row, column) && row[column] !== undefined) { return resolver(parent, args, context, info); } return gated(parent, args, context, info); }; } } /** A falsy selection means the field selects nothing from the parent row. */ function wrapSelect(selected: {} | null) { return selected ? { columns: {}, ...selected } : null; } SchemaBuilder.registerPlugin(pluginName, PothosDrizzlePlugin, {});