@nestjs/graphql
Version:
GraphQL for NestJS: code-first and schema-first APIs, resolvers as providers, subscriptions, federation and generated SDL, on Apollo or Mercurius.
433 lines (432 loc) • 21.2 kB
JavaScript
var GraphQLFederationFactory_1;
import { __decorate, __metadata } from "tslib";
import { mergeResolvers } from '@graphql-tools/merge';
import { mergeSchemas, addResolversToSchema } from '@graphql-tools/schema';
import { printSchemaWithDirectives } from '@graphql-tools/utils';
import { Injectable, Logger } from '@nestjs/common';
import { loadPackage } from '@nestjs/common/utils/load-package.util.js';
import { isString } from '@nestjs/common/utils/shared.utils.js';
import { GraphQLInterfaceType, GraphQLObjectType, GraphQLUnionType, isEnumType, isInputObjectType, isInterfaceType, isObjectType, isScalarType, isSpecifiedScalarType, isUnionType, specifiedDirectives, } from 'graphql';
import { gql } from 'graphql-tag';
import { createRequire } from 'module';
import { RESOLVER_REFERENCE_KEY } from '../graphql.constants.js';
import { GraphQLSchemaBuilder } from '../graphql-schema.builder.js';
import { ResolversExplorerService, ScalarsExplorerService, } from '../services/index.js';
import { backfillDefaultValues } from '../utils/backfill-default-values.util.js';
import { createFieldResolverBinder, inheritResolversFromInterfaces, } from '../utils/resolver-binding.util.js';
import { transformSchema } from '../utils/transform-schema.util.js';
import { federationV1Directives } from './federation-directives.js';
import { TypeDefsDecoratorFactory } from './type-defs-decorator.factory.js';
const DEFAULT_FEDERATION_VERSION = 1;
const nodeRequire = createRequire(import.meta.url);
/**
* @publicApi
*/
let GraphQLFederationFactory = GraphQLFederationFactory_1 = class GraphQLFederationFactory {
constructor(resolversExplorerService, scalarsExplorerService, gqlSchemaBuilder, typeDefsDecoratorFactory) {
this.resolversExplorerService = resolversExplorerService;
this.scalarsExplorerService = scalarsExplorerService;
this.gqlSchemaBuilder = gqlSchemaBuilder;
this.typeDefsDecoratorFactory = typeDefsDecoratorFactory;
this.logger = new Logger(GraphQLFederationFactory_1.name);
}
async generateSchema(options = {}, buildFederatedSchema) {
if (options.directiveResolvers) {
this.logger.warn('The "directiveResolvers" option is ignored (it has had no effect since v9.2.0): the directive resolvers passed through it are never called. Apply the directives with "transformSchema" instead (for example, with "mapSchema()" from "@graphql-tools/utils").');
}
const transformSchema = options.transformSchema ?? ((schema) => schema);
let schema;
if (options.autoSchemaFile) {
schema = await this.generateSchemaFromCodeFirst(options, buildFederatedSchema);
}
else if (this.isEmptyValue(options.typeDefs)) {
schema = options.schema;
}
else {
schema = await this.buildSchemaFromTypeDefs(options);
}
return await transformSchema(schema);
}
async buildSchemaFromTypeDefs(options) {
const { buildSubgraphSchema } = await loadPackage('@apollo/subgraph', 'ApolloFederation', () => import('@apollo/subgraph'));
const resolvers = await this.getResolvers(options);
const schema = addResolversToSchema({
resolverValidationOptions: options.resolverValidationOptions,
inheritResolversFromInterfaces: options.inheritResolversFromInterfaces,
resolvers,
schema: buildSubgraphSchema([
{
typeDefs: gql `
${options.typeDefs}
`,
resolvers: this.getReferenceResolvers(resolvers),
},
]),
});
if (options.inheritResolversFromInterfaces) {
inheritResolversFromInterfaces(schema, resolvers);
}
return schema;
}
async generateSchemaFromCodeFirst(options, buildFederatedSchema) {
const { subgraph: apolloSubgraph, majorVersion: apolloSubgraphMajorVersion, } = await this.loadApolloSubgraph();
const printSubgraphSchema = apolloSubgraph.printSubgraphSchema;
if (!buildFederatedSchema) {
buildFederatedSchema = ({ typeDefs, resolvers }) => apolloSubgraph.buildSubgraphSchema([{ typeDefs, resolvers }]);
}
const autoGeneratedSchema = await this.buildFederatedSchema(options.autoSchemaFile, options, this.resolversExplorerService.getAllCtors());
let typeDefs = apolloSubgraphMajorVersion >= 2
? printSchemaWithDirectives(backfillDefaultValues(autoGeneratedSchema))
: printSubgraphSchema(autoGeneratedSchema);
const [federationVersion, federationOptions] = this.getFederationVersionAndConfig(options.autoSchemaFile);
const typeDefsDecorator = this.typeDefsDecoratorFactory.create(federationVersion, apolloSubgraphMajorVersion);
if (typeDefsDecorator) {
typeDefs = typeDefsDecorator.decorate(typeDefs, federationOptions);
}
const resolvers = await this.getResolvers(options);
let executableSchema = addResolversToSchema({
schema: buildFederatedSchema({
typeDefs: gql(typeDefs),
resolvers: this.getReferenceResolvers(resolvers),
}),
resolvers,
resolverValidationOptions: options.resolverValidationOptions,
inheritResolversFromInterfaces: options.inheritResolversFromInterfaces,
});
executableSchema = this.overrideOrExtendResolvers(executableSchema, autoGeneratedSchema, resolvers, options.buildSchemaOptions?.fieldMiddleware ?? []);
const schema = options.schema
? mergeSchemas({
schemas: [options.schema, executableSchema],
})
: executableSchema;
return schema;
}
/**
* Collects the resolvers the same way "GraphQLFactory" does: the discovered
* resolvers are passed through "transformResolvers" and then merged with the
* "resolvers" option field by field, so that a type named in that option
* keeps the (enhancer-wrapped) field resolvers discovered for it.
*/
async getResolvers(options) {
const rawResolvers = [
...this.scalarsExplorerService.explore(),
this.resolversExplorerService.explore(),
];
const typesResolvers = options.transformResolvers
? await options.transformResolvers(rawResolvers)
: rawResolvers;
return mergeResolvers([typesResolvers, options.resolvers].flat().filter(Boolean));
}
/**
* "@apollo/subgraph" attaches resolvers to the schema in place, so custom
* scalars attached there would already be in effect when
* "addResolversToSchema" converts the (still raw) default values of the
* type definitions, running them through "serialize" before "parseValue".
* Hence only "__resolveReference", which "addResolversToSchema" cannot
* attach, is handed over to it.
*/
getReferenceResolvers(resolvers) {
return Object.fromEntries(Object.entries(resolvers)
.filter(([, typeResolvers]) => typeResolvers?.[RESOLVER_REFERENCE_KEY])
.map(([typeName, typeResolvers]) => [
typeName,
{ [RESOLVER_REFERENCE_KEY]: typeResolvers[RESOLVER_REFERENCE_KEY] },
]));
}
overrideOrExtendResolvers(executableSchema, autoGeneratedSchema, resolvers, globalMiddleware) {
const rootTypeNames = new Set([
autoGeneratedSchema.getQueryType(),
autoGeneratedSchema.getMutationType(),
autoGeneratedSchema.getSubscriptionType(),
]
.filter(Boolean)
.map(({ name }) => name));
// Created before any field is rebound below, as it reads the resolvers
// that "executableSchema" binds to the fields
const binder = createFieldResolverBinder({
executableSchema,
resolvers,
getType: (typeName) => autoGeneratedSchema.getType(typeName),
globalMiddleware,
});
const schema = transformSchema(executableSchema, (type) => {
if (isUnionType(type) && type.name !== '_Entity') {
return this.overrideFederatedResolveType(type, autoGeneratedSchema);
}
else if (isInterfaceType(type)) {
return this.overrideFederatedResolveType(type, autoGeneratedSchema);
}
else if (isEnumType(type)) {
return autoGeneratedSchema.getType(type.name);
}
else if (isInputObjectType(type)) {
const autoGeneratedInputType = autoGeneratedSchema.getType(type.name);
if (!autoGeneratedInputType) {
return type;
}
const fields = type.getFields();
Object.entries(fields).forEach(([key, value]) => {
const field = autoGeneratedInputType.getFields()[key];
if (!field) {
return;
}
value.extensions = field.extensions;
value.astNode = field.astNode;
});
type.extensions = autoGeneratedInputType.extensions;
return type;
}
else if (isObjectType(type)) {
const autoGeneratedObjectType = autoGeneratedSchema.getType(type.name);
if (!autoGeneratedObjectType) {
return type;
}
const fields = type.getFields();
Object.entries(fields).forEach(([key, value]) => {
const field = autoGeneratedObjectType.getFields()[key];
if (!field) {
return;
}
value.extensions = field.extensions;
value.astNode = field.astNode;
value.args.forEach((arg) => {
const autoGeneratedArg = field.args.find(({ name }) => name === arg.name);
if (autoGeneratedArg) {
arg.extensions = autoGeneratedArg.extensions;
}
});
if (rootTypeNames.has(type.name)) {
value.resolve ??= field.resolve;
return;
}
// Bind the resolvers the way "GraphQLFactory" does
value.resolve =
binder.getFieldResolver(type.name, key) ?? field.resolve;
});
if (autoGeneratedObjectType.astNode) {
type.astNode = {
...type.astNode,
...autoGeneratedObjectType.astNode,
};
}
type.extensions = {
...type.extensions,
...autoGeneratedObjectType.extensions,
};
return type;
}
else if (isScalarType(type) && !isSpecifiedScalarType(type)) {
// Scalars rebuilt from the printed SDL lose their implementation
// (e.g., "DateTime", "Timestamp" or any scalar from "scalarsMap")
const autoGeneratedScalar = autoGeneratedSchema.getType(type.name);
if (!autoGeneratedScalar) {
return type;
}
type.parseLiteral = autoGeneratedScalar.parseLiteral;
type.parseValue = autoGeneratedScalar.parseValue;
type.serialize = autoGeneratedScalar.serialize;
// graphql v17 coerces values through `coerce*` methods, which are
// separate from their deprecated `serialize`/`parse*` counterparts.
copyCoercionMethods(autoGeneratedScalar, type);
return type;
}
return type;
});
binder.warnUnboundFields(this.logger);
// The federated schema was built from the printed SDL, so its default
// values were coerced with the enums and scalars of that schema (an enum
// value is its name, a "DateTime" stays a string). Now that the
// auto-generated types are back in place, put the declared defaults back.
restoreDefaultValues(autoGeneratedSchema, schema);
return schema;
}
/**
* Ensures that the resolveType method for unions and interfaces in the federated schema
* is properly set from the one in the autoGeneratedSchema.
*/
overrideFederatedResolveType(typeInFederatedSchema, autoGeneratedSchema) {
// Get the matching type from the auto generated schema
const autoGeneratedType = autoGeneratedSchema.getType(typeInFederatedSchema.name);
// Bail if inconsistent with original schema
if (!autoGeneratedType ||
!(autoGeneratedType instanceof GraphQLUnionType ||
autoGeneratedType instanceof GraphQLInterfaceType) ||
!autoGeneratedType.resolveType) {
return typeInFederatedSchema;
}
typeInFederatedSchema.resolveType = async (value, context, info, abstractType) => {
const resultFromAutogenSchema = await autoGeneratedType.resolveType(value, context, info, abstractType);
// If the result is not a GraphQLObjectType we're fine
if (!resultFromAutogenSchema || isString(resultFromAutogenSchema)) {
return resultFromAutogenSchema;
}
// We now have a GraphQLObjectType from the original union in the autogenerated schema.
// But we can't return that without the additional federation property apollo adds to object
// types (see node_modules/@apollo/federation/src/composition/types.ts:47).
// Without that property, Apollo will ignore the returned type and the
// union value will resolve to null. So we need to return the type with
// the same name from the federated schema
const resultFromFederatedSchema = info.schema.getType(resultFromAutogenSchema.name);
if (resultFromFederatedSchema &&
resultFromFederatedSchema instanceof GraphQLObjectType) {
return resultFromFederatedSchema;
}
// If we couldn't find a match in the federated schema, return just the
// name of the type and hope apollo works it out
return resultFromAutogenSchema;
};
return typeInFederatedSchema;
}
async buildFederatedSchema(autoSchemaFile, options, resolvers) {
const scalarsMap = this.scalarsExplorerService.getScalarsMap();
try {
const buildSchemaOptions = options.buildSchemaOptions || {};
const directives = [...specifiedDirectives];
const [federationVersion] = this.getFederationVersionAndConfig(autoSchemaFile);
if (federationVersion < 2) {
directives.push(...federationV1Directives);
}
if (buildSchemaOptions?.directives) {
directives.push(...buildSchemaOptions.directives);
}
// Same options as "GraphQLSchemaBuilder.build()" plus the federation directives
return await this.gqlSchemaBuilder.generateSchema(resolvers, autoSchemaFile, {
...buildSchemaOptions,
directives,
scalarsMap: [
...(buildSchemaOptions.scalarsMap ?? []),
...scalarsMap.filter(({ type }) => buildSchemaOptions.scalarsMap?.every((item) => item.type !== type) ?? true),
],
skipCheck: true,
// Pass include modules for type filtering in Code First approach
// This property is handled internally by GraphQLSchemaFactory
includeModules: options.include,
}, options.sortSchema, options.transformAutoSchemaFile && options.transformSchema, await this.getFederationSchemaPrinter(autoSchemaFile));
}
catch (err) {
if (err && err.details) {
console.error(err.details);
}
throw err;
}
}
async loadApolloSubgraph() {
const subgraph = await loadPackage('@apollo/subgraph', 'ApolloFederation', () => import('@apollo/subgraph'));
const { version } = nodeRequire('@apollo/subgraph/package.json');
return { subgraph, majorVersion: Number(version.split('.')[0]) };
}
async getFederationSchemaPrinter(autoSchemaFile) {
const { subgraph, majorVersion } = await this.loadApolloSubgraph();
const print = majorVersion >= 2
? (schema) => printSchemaWithDirectives(schema)
: subgraph.printSubgraphSchema;
const [federationVersion, federationOptions] = this.getFederationVersionAndConfig(autoSchemaFile);
const typeDefsDecorator = this.typeDefsDecoratorFactory.create(federationVersion, majorVersion);
if (!typeDefsDecorator) {
return print;
}
// Link the federation spec in the emitted file too, so that the file can be
// composed (e.g., with "rover") as the federation 2 subgraph it is served as.
// The decorator indents the printed schema, hence the whitespace clean-up.
return (schema) => typeDefsDecorator
.decorate(print(schema), federationOptions)
.trim()
.replace(/\n\s*/, '\n\n');
}
getFederationVersionAndConfig(autoSchemaFile) {
if (!autoSchemaFile || typeof autoSchemaFile !== 'object') {
return [DEFAULT_FEDERATION_VERSION];
}
if (typeof autoSchemaFile.federation !== 'object') {
return [autoSchemaFile.federation ?? DEFAULT_FEDERATION_VERSION];
}
return [
autoSchemaFile.federation?.version ?? DEFAULT_FEDERATION_VERSION,
autoSchemaFile.federation,
];
}
isEmptyValue(value) {
if (value == null) {
return true;
}
if (Array.isArray(value) || typeof value === 'string') {
return value.length === 0;
}
return false;
}
};
GraphQLFederationFactory = GraphQLFederationFactory_1 = __decorate([
Injectable(),
__metadata("design:paramtypes", [ResolversExplorerService,
ScalarsExplorerService,
GraphQLSchemaBuilder,
TypeDefsDecoratorFactory])
], GraphQLFederationFactory);
export { GraphQLFederationFactory };
function restoreDefaultValues(autoGeneratedSchema, schema) {
for (const directive of schema.getDirectives()) {
const autoGeneratedDirective = autoGeneratedSchema.getDirective(directive.name);
if (autoGeneratedDirective) {
restoreArgDefaultValues(autoGeneratedDirective.args, directive.args);
}
}
for (const type of Object.values(schema.getTypeMap())) {
const autoGeneratedType = autoGeneratedSchema.getType(type.name);
if ((isObjectType(type) || isInterfaceType(type)) &&
(isObjectType(autoGeneratedType) || isInterfaceType(autoGeneratedType))) {
const autoGeneratedFields = autoGeneratedType.getFields();
for (const [key, field] of Object.entries(type.getFields())) {
const autoGeneratedField = autoGeneratedFields[key];
if (autoGeneratedField) {
restoreArgDefaultValues(autoGeneratedField.args, field.args);
}
}
}
else if (isInputObjectType(type) &&
isInputObjectType(autoGeneratedType)) {
const autoGeneratedFields = autoGeneratedType.getFields();
for (const [key, field] of Object.entries(type.getFields())) {
const autoGeneratedField = autoGeneratedFields[key];
if (autoGeneratedField) {
restoreDefaultValue(autoGeneratedField, field);
}
}
}
}
}
function restoreArgDefaultValues(source, target) {
for (const arg of target) {
const sourceArg = source.find(({ name }) => name === arg.name);
if (sourceArg) {
restoreDefaultValue(sourceArg, arg);
}
}
}
function restoreDefaultValue(source, target) {
if (source.defaultValue === undefined) {
return;
}
target.defaultValue = source.defaultValue;
// graphql v17 reads argument and input field defaults from the `default`
// property (see "backfillDefaultValues")
const sourceHolder = source;
const targetHolder = target;
if ('default' in targetHolder) {
targetHolder.default = sourceHolder.default ?? {
value: source.defaultValue,
};
}
}
function copyCoercionMethods(source, target) {
const sourceMethods = source;
const targetMethods = target;
for (const method of [
'coerceOutputValue',
'coerceInputValue',
'coerceInputLiteral',
]) {
if (typeof sourceMethods[method] === 'function') {
targetMethods[method] = sourceMethods[method];
}
}
}