import './global-types.js'; import './schema-builder.js'; import SchemaBuilder, { BasePlugin, type RootName, type SchemaTypes } from '@pothos/core'; import { type GraphQLNamedType, type GraphQLObjectType, GraphQLSchema } from 'graphql'; import { mergeGraphQLObjectFields } from './schema-builder.js'; import { addTypeToSchema, importedTypes, isUnintendedRoot } from './utils.js'; const pluginName = 'addGraphQL'; export default pluginName; const builtInTypes = Object.keys(new GraphQLSchema({}).getTypeMap()); export class PothosAddGraphQLPlugin extends BasePlugin { override beforeBuild(): void { const { schema, types } = this.builder.options.add ?? {}; const rootKinds = new Map(); if (schema) { const roots: [RootName, GraphQLNamedType | null | undefined][] = [ ['Query', schema.getQueryType()], ['Mutation', schema.getMutationType()], ['Subscription', schema.getSubscriptionType()], ]; for (const [kind, rootType] of roots) { if (rootType) { rootKinds.set(rootType, kind); } } } for (const type of Array.isArray(types) ? types : Object.values(types ?? {})) { addTypeToSchema(this.builder, type, rootKinds.get(type)); } const schemaTypes = Object.values(schema?.getTypeMap() ?? {}).filter( (type) => !builtInTypes.includes(type.name), ); const imported = importedTypes(this.builder); for (const type of schemaTypes) { if (imported.has(type)) { continue; } if (rootKinds.has(type) && this.builder.configStore.hasConfig(type.name as never)) { mergeGraphQLObjectFields(this.builder, type as GraphQLObjectType, rootKinds.get(type)!); imported.add(type); } else { addTypeToSchema(this.builder, type, rootKinds.get(type) ?? null); } } } override afterBuild(schema: GraphQLSchema): GraphQLSchema { const removeQuery = isUnintendedRoot(this.builder, schema.getQueryType(), 'Query'); const removeMutation = isUnintendedRoot(this.builder, schema.getMutationType(), 'Mutation'); const removeSubscription = isUnintendedRoot( this.builder, schema.getSubscriptionType(), 'Subscription', ); if (!removeQuery && !removeMutation && !removeSubscription) { return schema; } const config = schema.toConfig(); return new GraphQLSchema({ ...config, query: removeQuery ? undefined : config.query, mutation: removeMutation ? undefined : config.mutation, subscription: removeSubscription ? undefined : config.subscription, }); } } SchemaBuilder.registerPlugin(pluginName, PothosAddGraphQLPlugin);