From d7a655ce86abc315e2cda32185a6b6e2fba388e3 Mon Sep 17 00:00:00 2001 From: Rafael Escobar Date: Mon, 21 Sep 2026 10:59:29 -0300 Subject: [PATCH 1/2] fix: changes in `buildSubgraphSchema` --- .../graphql/lib/federation/graphql-federation.factory.ts | 3 ++- .../lib/utils/build-mercurius-federated-schema.util.ts | 7 +++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/graphql/lib/federation/graphql-federation.factory.ts b/packages/graphql/lib/federation/graphql-federation.factory.ts index 750b0767c..f9d2c6e62 100644 --- a/packages/graphql/lib/federation/graphql-federation.factory.ts +++ b/packages/graphql/lib/federation/graphql-federation.factory.ts @@ -124,7 +124,8 @@ export class GraphQLFederationFactory { const printSubgraphSchema = apolloSubgraph.printSubgraphSchema; if (!buildFederatedSchema) { - buildFederatedSchema = apolloSubgraph.buildSubgraphSchema; + buildFederatedSchema = ({ typeDefs, resolvers }) => + apolloSubgraph.buildSubgraphSchema([{ typeDefs, resolvers }]); } const autoGeneratedSchema: GraphQLSchema = await this.buildFederatedSchema( diff --git a/packages/mercurius/lib/utils/build-mercurius-federated-schema.util.ts b/packages/mercurius/lib/utils/build-mercurius-federated-schema.util.ts index 5df062248..f3b0af7fe 100644 --- a/packages/mercurius/lib/utils/build-mercurius-federated-schema.util.ts +++ b/packages/mercurius/lib/utils/build-mercurius-federated-schema.util.ts @@ -14,10 +14,9 @@ export function buildMercuriusFederatedSchema({ 'MercuriusFederation', () => nodeRequire('@apollo/subgraph'), ); - let executableSchema: GraphQLSchema = buildSubgraphSchema({ - typeDefs, - resolvers, - }); + let executableSchema: GraphQLSchema = buildSubgraphSchema([ + { typeDefs, resolvers }, + ]); const subscriptionResolvers = resolvers.Subscription; executableSchema = transformSchema(executableSchema, (type) => { From 09891f4f712c9626abcaf7f09910d2d2e2241e33 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kamil=20My=C5=9Bliwiec?= Date: Tue, 22 Sep 2026 09:15:12 +0200 Subject: [PATCH 2/2] fix: support @apollo/subgraph v2.15 - inline the Federation 1 directive definitions, as "@apollo/subgraph/dist/directives" no longer exists - omit the federation types and schema definition that "printSubgraphSchema" now prints when generating definitions - print the mercurius `_service` SDL without relying on "printSubgraphSchema", whose output changed, and without the stub definitions that "buildSubgraphSchema" now adds for extension-only types, which "@mercuriusjs/gateway" doesn't support - bump @apollo/subgraph to 2.15.1 Co-Authored-By: Claude Opus 5 --- packages/apollo/package.json | 2 +- .../code-first-federation.spec.ts.snap | 55 +----- .../federation-typedef.fixture.ts | 8 +- .../federation.fixture.ts | 8 +- .../lib/federation/federation-directives.ts | 168 ++++++++++++++++++ .../graphql-federation-definitions.factory.ts | 57 +++++- .../federation/graphql-federation.factory.ts | 38 +--- packages/graphql/package.json | 2 +- .../drivers/mercurius-federation.driver.ts | 17 +- .../build-mercurius-federated-schema.util.ts | 11 +- .../lib/utils/print-subgraph-sdl.util.ts | 45 +++++ .../tests/e2e/code-first-federation.spec.ts | 9 +- yarn.lock | 16 +- 13 files changed, 313 insertions(+), 123 deletions(-) create mode 100644 packages/graphql/lib/federation/federation-directives.ts create mode 100644 packages/mercurius/lib/utils/print-subgraph-sdl.util.ts diff --git a/packages/apollo/package.json b/packages/apollo/package.json index 747188dbc..e7f75cab2 100644 --- a/packages/apollo/package.json +++ b/packages/apollo/package.json @@ -35,7 +35,7 @@ "@apollo/gateway": "2.14.4", "@apollo/server": "5.5.1", "@apollo/server-plugin-response-cache": "5.0.0", - "@apollo/subgraph": "2.14.4", + "@apollo/subgraph": "2.15.1", "@as-integrations/express5": "^1.1.2", "@as-integrations/fastify": "3.1.0", "@nestjs/common": "12.0.3", diff --git a/packages/apollo/tests/e2e/__snapshots__/code-first-federation.spec.ts.snap b/packages/apollo/tests/e2e/__snapshots__/code-first-federation.spec.ts.snap index d397f853e..6ff194e0e 100644 --- a/packages/apollo/tests/e2e/__snapshots__/code-first-federation.spec.ts.snap +++ b/packages/apollo/tests/e2e/__snapshots__/code-first-federation.spec.ts.snap @@ -3,30 +3,9 @@ exports[`Code-first - Federation > should return query result 1`] = ` { "_service": { - "sdl": """" -Designates an object type as an entity and specifies its key fields. Key fields are a set of fields that a subgraph can use to uniquely identify any instance of the entity. -""" -directive @key(fields: String!, resolvable: Boolean = true) repeatable on OBJECT | INTERFACE - -""" -Indicates that an object or interface definition is an extension of another definition of that same type. This directive is for use with GraphQL subgraph libraries that do not support the extend keyword. Most commonly, these are subgraph libraries that generate their schema programmatically instead of using a static .graphql file. -""" -directive @extends on OBJECT | INTERFACE - -""" -Indicates that this subgraph usually can't resolve a particular object field, but it still needs to define that field for other purposes. This directive is always used in combination with another directive that references object fields, such as @provides or @requires. -""" -directive @external on OBJECT | FIELD_DEFINITION - -""" -Indicates that the resolver for a particular entity field depends on the values of other entity fields that are resolved by other subgraphs. This tells the router that it needs to fetch the values of those externally defined fields first, even if the original client query didn't request them. -""" -directive @requires(fields: String!) on FIELD_DEFINITION - -""" -Specifies a set of entity fields that a subgraph can resolve, but only at a particular schema path (at other paths, the subgraph can't resolve those fields). If a subgraph can always resolve a particular entity field, do not apply this directive. Using this directive is always an optional optimization. It can reduce the total number of subgraphs that your router needs to communicate with to resolve certain operations, which can improve performance. -""" -directive @provides(fields: String!) on FIELD_DEFINITION + "sdl": "schema { + query: Query +} """ Indicates that an object type's field is allowed to be resolved by multiple subgraphs (by default in Federation 2, object fields can be resolved by only one subgraph). @@ -38,11 +17,6 @@ This directive links definitions from an external specification to this schema. """ directive @link(url: String!, import: [link__Import]) on SCHEMA -""" -Applies arbitrary string metadata to a schema location. Custom tooling can use this metadata during any step of the schema delivery flow, including composition, static analysis, and documentation. The GraphOS Enterprise contracts feature uses @tag with its inclusion and exclusion filters. -""" -directive @tag(name: String!) repeatable on FIELD_DEFINITION | OBJECT | INTERFACE | UNION | ARGUMENT_DEFINITION | SCALAR | ENUM | ENUM_VALUE | INPUT_OBJECT | INPUT_FIELD_DEFINITION - """ Indicates that a definition in the subgraph schema should be omitted from the router's API schema, even if that definition is also present in other subgraphs. This means that the field is not exposed to clients at all. """ @@ -59,18 +33,13 @@ interface IRecipe { externalField: String! @external } -type Post - @key(fields: "id") -{ +type Post @key(fields: "id") { id: ID! title: String! authorId: Int! } -type User - @extends - @key(fields: "id") -{ +type User @extends @key(fields: "id") { id: ID! @external posts: [Post!]! } @@ -100,24 +69,12 @@ type Query { search: [FederationSearchResultUnion!]! @deprecated(reason: "test") recipe: IRecipe! humans: [Human!]! - _entities(representations: [_Any!]!): [_Entity]! - _service: _Service! } """Search result description""" union FederationSearchResultUnion = Post | User -scalar link__Import - -scalar _FieldSet - -scalar _Any - -type _Service { - sdl: String -} - -union _Entity = Post | User", +scalar link__Import", }, } `; diff --git a/packages/apollo/tests/generated-definitions/federation-typedef.fixture.ts b/packages/apollo/tests/generated-definitions/federation-typedef.fixture.ts index 077085215..23f37181a 100644 --- a/packages/apollo/tests/generated-definitions/federation-typedef.fixture.ts +++ b/packages/apollo/tests/generated-definitions/federation-typedef.fixture.ts @@ -24,13 +24,13 @@ export class Post { category: Category; } -export abstract class IQuery { - abstract getPosts(): Nullable[]> | Promise[]>>; -} - export class User { id: string; posts?: Nullable[]>; } +export abstract class IQuery { + abstract getPosts(): Nullable[]> | Promise[]>>; +} + type Nullable = T | null; diff --git a/packages/apollo/tests/generated-definitions/federation.fixture.ts b/packages/apollo/tests/generated-definitions/federation.fixture.ts index c662cbee0..66cc096d2 100644 --- a/packages/apollo/tests/generated-definitions/federation.fixture.ts +++ b/packages/apollo/tests/generated-definitions/federation.fixture.ts @@ -19,13 +19,13 @@ export class Post { category: Category; } -export abstract class IQuery { - abstract getPosts(): Nullable[]> | Promise[]>>; -} - export class User { id: string; posts?: Nullable[]>; } +export abstract class IQuery { + abstract getPosts(): Nullable[]> | Promise[]>>; +} + type Nullable = T | null; diff --git a/packages/graphql/lib/federation/federation-directives.ts b/packages/graphql/lib/federation/federation-directives.ts new file mode 100644 index 000000000..0a7b7bfaf --- /dev/null +++ b/packages/graphql/lib/federation/federation-directives.ts @@ -0,0 +1,168 @@ +import { + DirectiveLocation, + GraphQLBoolean, + GraphQLDirective, + GraphQLList, + GraphQLNonNull, + GraphQLScalarType, + GraphQLString, +} from 'graphql'; + +/** + * Federation directive definitions inlined into Federation 1 schemas generated + * using the code-first approach. Mirrors the definitions that "@apollo/subgraph" + * exported from "dist/directives" until v2.15, which no longer exposes them. + */ +const LinkImportType = new GraphQLScalarType({ + name: 'link__Import', + specifiedByURL: null, +}); + +const KeyDirective = new GraphQLDirective({ + name: 'key', + description: + 'Designates an object type as an entity and specifies its key fields. Key fields are a set of fields that a subgraph can use to uniquely identify any instance of the entity.', + locations: [DirectiveLocation.OBJECT, DirectiveLocation.INTERFACE], + isRepeatable: true, + args: { + fields: { + type: new GraphQLNonNull(GraphQLString), + }, + resolvable: { + type: GraphQLBoolean, + defaultValue: true, + }, + }, +}); + +const ExtendsDirective = new GraphQLDirective({ + name: 'extends', + description: + 'Indicates that an object or interface definition is an extension of another definition of that same type. This directive is for use with GraphQL subgraph libraries that do not support the extend keyword. Most commonly, these are subgraph libraries that generate their schema programmatically instead of using a static .graphql file.', + locations: [DirectiveLocation.OBJECT, DirectiveLocation.INTERFACE], +}); + +const ExternalDirective = new GraphQLDirective({ + name: 'external', + description: + "Indicates that this subgraph usually can't resolve a particular object field, but it still needs to define that field for other purposes. This directive is always used in combination with another directive that references object fields, such as @provides or @requires.", + locations: [DirectiveLocation.OBJECT, DirectiveLocation.FIELD_DEFINITION], +}); + +const RequiresDirective = new GraphQLDirective({ + name: 'requires', + description: + "Indicates that the resolver for a particular entity field depends on the values of other entity fields that are resolved by other subgraphs. This tells the router that it needs to fetch the values of those externally defined fields first, even if the original client query didn't request them.", + locations: [DirectiveLocation.FIELD_DEFINITION], + args: { + fields: { + type: new GraphQLNonNull(GraphQLString), + }, + }, +}); + +const ProvidesDirective = new GraphQLDirective({ + name: 'provides', + description: + "Specifies a set of entity fields that a subgraph can resolve, but only at a particular schema path (at other paths, the subgraph can't resolve those fields). If a subgraph can always resolve a particular entity field, do not apply this directive. Using this directive is always an optional optimization. It can reduce the total number of subgraphs that your router needs to communicate with to resolve certain operations, which can improve performance.", + locations: [DirectiveLocation.FIELD_DEFINITION], + args: { + fields: { + type: new GraphQLNonNull(GraphQLString), + }, + }, +}); + +const ShareableDirective = new GraphQLDirective({ + name: 'shareable', + description: + "Indicates that an object type's field is allowed to be resolved by multiple subgraphs (by default in Federation 2, object fields can be resolved by only one subgraph).", + locations: [DirectiveLocation.FIELD_DEFINITION, DirectiveLocation.OBJECT], +}); + +const LinkDirective = new GraphQLDirective({ + name: 'link', + description: + 'This directive links definitions from an external specification to this schema.', + locations: [DirectiveLocation.SCHEMA], + args: { + url: { + type: new GraphQLNonNull(GraphQLString), + }, + import: { + type: new GraphQLList(LinkImportType), + }, + }, +}); + +// The Federation 2 tag spec also allows "@tag" on SCHEMA, but that location +// isn't valid in Federation 1 schemas, so it's intentionally left out here. +const TagDirective = new GraphQLDirective({ + name: 'tag', + description: + 'Applies arbitrary string metadata to a schema location. Custom tooling can use this metadata during any step of the schema delivery flow, including composition, static analysis, and documentation. The GraphOS Enterprise contracts feature uses @tag with its inclusion and exclusion filters.', + locations: [ + DirectiveLocation.FIELD_DEFINITION, + DirectiveLocation.OBJECT, + DirectiveLocation.INTERFACE, + DirectiveLocation.UNION, + DirectiveLocation.ARGUMENT_DEFINITION, + DirectiveLocation.SCALAR, + DirectiveLocation.ENUM, + DirectiveLocation.ENUM_VALUE, + DirectiveLocation.INPUT_OBJECT, + DirectiveLocation.INPUT_FIELD_DEFINITION, + ], + isRepeatable: true, + args: { + name: { + type: new GraphQLNonNull(GraphQLString), + }, + }, +}); + +const InaccessibleDirective = new GraphQLDirective({ + name: 'inaccessible', + description: + "Indicates that a definition in the subgraph schema should be omitted from the router's API schema, even if that definition is also present in other subgraphs. This means that the field is not exposed to clients at all.", + locations: [ + DirectiveLocation.FIELD_DEFINITION, + DirectiveLocation.OBJECT, + DirectiveLocation.INTERFACE, + DirectiveLocation.UNION, + DirectiveLocation.ARGUMENT_DEFINITION, + DirectiveLocation.SCALAR, + DirectiveLocation.ENUM, + DirectiveLocation.ENUM_VALUE, + DirectiveLocation.INPUT_OBJECT, + DirectiveLocation.INPUT_FIELD_DEFINITION, + ], +}); + +const OverrideDirective = new GraphQLDirective({ + name: 'override', + description: + "Indicates that an object field is now resolved by this subgraph instead of another subgraph where it's also defined. This enables you to migrate a field from one subgraph to another.", + locations: [DirectiveLocation.FIELD_DEFINITION], + args: { + from: { + type: new GraphQLNonNull(GraphQLString), + }, + label: { + type: GraphQLString, + }, + }, +}); + +export const federationV1Directives: GraphQLDirective[] = [ + KeyDirective, + ExtendsDirective, + ExternalDirective, + RequiresDirective, + ProvidesDirective, + ShareableDirective, + LinkDirective, + TagDirective, + InaccessibleDirective, + OverrideDirective, +]; diff --git a/packages/graphql/lib/federation/graphql-federation-definitions.factory.ts b/packages/graphql/lib/federation/graphql-federation-definitions.factory.ts index fef6b8019..26dccb83c 100644 --- a/packages/graphql/lib/federation/graphql-federation-definitions.factory.ts +++ b/packages/graphql/lib/federation/graphql-federation-definitions.factory.ts @@ -1,10 +1,17 @@ import { mergeTypeDefs } from '@graphql-tools/merge'; import { loadPackage } from '@nestjs/common/utils/load-package.util.js'; +import { DefinitionNode, DocumentNode, Kind, parse } from 'graphql'; import { gql } from 'graphql-tag'; import { DefinitionsGeneratorOptions } from '../graphql-ast.explorer.js'; import { GraphQLDefinitionsFactory } from '../graphql-definitions.factory.js'; import { extend } from '../utils/index.js'; +const DEFAULT_ROOT_TYPE_NAMES: Record = { + query: 'Query', + mutation: 'Mutation', + subscription: 'Subscription', +}; + /** * @publicApi */ @@ -29,19 +36,24 @@ export class GraphQLFederationDefinitionsFactory extends GraphQLDefinitionsFacto () => import('@apollo/subgraph'), ); + const typeDefsDocument = gql` + ${mergedTypeDefs} + `; const schema = buildSubgraphSchema([ { - typeDefs: gql` - ${mergedTypeDefs} - `, + typeDefs: typeDefsDocument, resolvers: {}, }, ]); + const subgraphDocument = this.omitFederationDefinitions( + parse(printSubgraphSchema(schema)), + typeDefsDocument, + ); // "buildSubgraphSchema" generates an empty Query definition if there is the `extend type Query` statement // This leads to duplicated IQuery interfaces // see: https://github.com//issues/2344 - const mergedDefinition = mergeTypeDefs([printSubgraphSchema(schema)], { + const mergedDefinition = mergeTypeDefs([subgraphDocument], { useSchemaDefinition: false, throwOnConflict: true, commentDescriptions: true, @@ -62,4 +74,41 @@ export class GraphQLFederationDefinitionsFactory extends GraphQLDefinitionsFacto isDebugEnabled, ); } + + /** + * Since v2.15, "printSubgraphSchema" prints the entire subgraph schema, including + * the types, root fields and schema definition that federation adds on top of + * the user-provided type definitions. Drop everything the type definitions + * don't declare themselves so the generated output matches earlier versions. + */ + private omitFederationDefinitions( + subgraphDocument: DocumentNode, + typeDefsDocument: DocumentNode, + ): DocumentNode { + const declaredNames = new Set( + typeDefsDocument.definitions.map((definition) => + this.getDefinitionName(definition), + ), + ); + const definitions = subgraphDocument.definitions.filter((definition) => { + if (definition.kind === Kind.SCHEMA_DEFINITION) { + // Same as "printSchema", omit the schema definition when it only uses the default root type names + return definition.operationTypes.some( + ({ operation, type }) => + type.name.value !== DEFAULT_ROOT_TYPE_NAMES[operation], + ); + } + const name = this.getDefinitionName(definition); + return ( + !name || + definition.kind === Kind.DIRECTIVE_DEFINITION || + declaredNames.has(name) + ); + }); + return { ...subgraphDocument, definitions }; + } + + private getDefinitionName(definition: DefinitionNode): string | undefined { + return 'name' in definition ? definition.name?.value : undefined; + } } diff --git a/packages/graphql/lib/federation/graphql-federation.factory.ts b/packages/graphql/lib/federation/graphql-federation.factory.ts index f9d2c6e62..8b8911fba 100644 --- a/packages/graphql/lib/federation/graphql-federation.factory.ts +++ b/packages/graphql/lib/federation/graphql-federation.factory.ts @@ -1,15 +1,10 @@ import { mergeSchemas, addResolversToSchema } from '@graphql-tools/schema'; import { printSchemaWithDirectives } from '@graphql-tools/utils'; import { Injectable } from '@nestjs/common'; -import { - loadPackage, - loadPackageSync, -} from '@nestjs/common/utils/load-package.util.js'; +import { loadPackage } from '@nestjs/common/utils/load-package.util.js'; import { isString } from '@nestjs/common/utils/shared.utils.js'; import { - DirectiveLocation, GraphQLAbstractType, - GraphQLDirective, GraphQLField, GraphQLInputField, GraphQLInputObjectType, @@ -44,6 +39,7 @@ import { import { extend } from '../utils/index.js'; import { backfillDefaultValues } from '../utils/backfill-default-values.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: FederationVersion = 1; @@ -354,7 +350,7 @@ export class GraphQLFederationFactory { this.getFederationVersionAndConfig(autoSchemaFile); if (federationVersion < 2) { - directives.push(...this.loadFederationDirectives()); + directives.push(...federationV1Directives); } if (buildSchemaOptions?.directives) { directives.push(...buildSchemaOptions.directives); @@ -420,34 +416,6 @@ export class GraphQLFederationFactory { ]; } - private loadFederationDirectives() { - const { federationDirectives, directivesWithNoDefinitionNeeded } = - loadPackageSync('@apollo/subgraph/dist/directives', 'SchemaBuilder', () => - nodeRequire('@apollo/subgraph/dist/directives'), - ); - const directives: GraphQLDirective[] = - federationDirectives ?? directivesWithNoDefinitionNeeded; - - // "@apollo/subgraph" >= 2.13 declares "@tag" on SCHEMA as well, but that location - // was only introduced by the Federation 2 tag spec. Since these definitions are - // inlined into Federation 1 schemas, drop it to keep such schemas valid. - return directives.map((directive) => { - if ( - directive.name !== 'tag' || - !directive.locations.includes(DirectiveLocation.SCHEMA) - ) { - return directive; - } - const config = directive.toConfig(); - return new GraphQLDirective({ - ...config, - locations: config.locations.filter( - (location) => location !== DirectiveLocation.SCHEMA, - ), - }); - }); - } - private isEmptyValue(value: unknown) { if (value == null) { return true; diff --git a/packages/graphql/package.json b/packages/graphql/package.json index 9f9fdb159..f9bbb0a09 100644 --- a/packages/graphql/package.json +++ b/packages/graphql/package.json @@ -59,7 +59,7 @@ "ws": "8.21.3" }, "devDependencies": { - "@apollo/subgraph": "2.14.4", + "@apollo/subgraph": "2.15.1", "@nestjs/common": "12.0.3", "@nestjs/core": "12.0.3", "@nestjs/testing": "12.0.3", diff --git a/packages/mercurius/lib/drivers/mercurius-federation.driver.ts b/packages/mercurius/lib/drivers/mercurius-federation.driver.ts index e44f9347f..6e9913eb7 100644 --- a/packages/mercurius/lib/drivers/mercurius-federation.driver.ts +++ b/packages/mercurius/lib/drivers/mercurius-federation.driver.ts @@ -4,11 +4,12 @@ import { GraphQLFederationFactory, } from '@nestjs/graphql'; import { FastifyBaseLogger, FastifyInstance } from 'fastify'; -import { GraphQLSchema, printSchema } from 'graphql'; +import { GraphQLSchema, parse, printSchema } from 'graphql'; import { IncomingMessage, Server, ServerResponse } from 'http'; import mercurius from 'mercurius'; import { MercuriusDriverConfig } from '../interfaces/mercurius-driver-config.interface.js'; import { buildMercuriusFederatedSchema } from '../utils/build-mercurius-federated-schema.util.js'; +import { printSubgraphSdl } from '../utils/print-subgraph-sdl.util.js'; import { registerMercuriusHooks } from '../utils/register-mercurius-hooks.util.js'; import { registerMercuriusRequestHooks } from '../utils/register-mercurius-request-hooks.util.js'; import { registerMercuriusPlugin } from '../utils/register-mercurius-plugin.util.js'; @@ -62,12 +63,22 @@ export class MercuriusFederationDriver extends AbstractGraphQLDriver {} - public generateSchema( + public async generateSchema( options: MercuriusDriverConfig, ): Promise { - return this.graphqlFederationFactory.generateSchema( + const schema = await this.graphqlFederationFactory.generateSchema( options, buildMercuriusFederatedSchema, ); + if (!options.autoSchemaFile && options.typeDefs?.length) { + // Schemas built from type definitions resolve `_service` through "@apollo/subgraph" + const typeDefs = [options.typeDefs].flat().join('\n'); + const sdl = printSubgraphSdl(parse(typeDefs)); + const serviceField = schema.getQueryType()?.getFields()._service; + if (serviceField) { + serviceField.resolve = () => ({ sdl }); + } + } + return schema; } } diff --git a/packages/mercurius/lib/utils/build-mercurius-federated-schema.util.ts b/packages/mercurius/lib/utils/build-mercurius-federated-schema.util.ts index f3b0af7fe..d2e5ae281 100644 --- a/packages/mercurius/lib/utils/build-mercurius-federated-schema.util.ts +++ b/packages/mercurius/lib/utils/build-mercurius-federated-schema.util.ts @@ -1,7 +1,8 @@ import { loadPackageSync } from '@nestjs/common/utils/load-package.util.js'; import { BuildFederatedSchemaOptions, transformSchema } from '@nestjs/graphql'; -import { buildASTSchema, GraphQLSchema, isObjectType } from 'graphql'; +import { GraphQLSchema, isObjectType } from 'graphql'; import { createRequire } from 'module'; +import { printSubgraphSdl } from './print-subgraph-sdl.util.js'; const nodeRequire = createRequire(import.meta.url); @@ -9,7 +10,7 @@ export function buildMercuriusFederatedSchema({ typeDefs, resolvers, }: BuildFederatedSchemaOptions) { - const { buildSubgraphSchema, printSubgraphSchema } = loadPackageSync( + const { buildSubgraphSchema } = loadPackageSync( '@apollo/subgraph', 'MercuriusFederation', () => nodeRequire('@apollo/subgraph'), @@ -32,11 +33,7 @@ export function buildMercuriusFederatedSchema({ // Workaround for https://github.com/mercurius-js/mercurius/issues/273 value.resolve = function resolve() { return { - sdl: printSubgraphSchema( - buildASTSchema(typeDefs, { - assumeValid: true, - }), - ) + sdl: printSubgraphSdl(typeDefs) .replace('type Query {', 'type Query @extends {') .replace('type Mutation {', 'type Mutation @extends {') .replace('type Subscription {', 'type Subscription @extends {'), diff --git a/packages/mercurius/lib/utils/print-subgraph-sdl.util.ts b/packages/mercurius/lib/utils/print-subgraph-sdl.util.ts new file mode 100644 index 000000000..df50e5659 --- /dev/null +++ b/packages/mercurius/lib/utils/print-subgraph-sdl.util.ts @@ -0,0 +1,45 @@ +import { DocumentNode, Kind, print } from 'graphql'; + +// Provided by the Federation 1 specification, so gateways expect subgraphs to not declare them +const FEDERATION_DIRECTIVE_NAMES = [ + 'key', + 'requires', + 'provides', + 'external', + 'extends', + 'tag', +]; +const FEDERATION_TYPE_NAMES = ['_FieldSet', '_Any', '_Service', '_Entity']; +const DEFAULT_ROOT_TYPE_NAMES: Record = { + query: 'Query', + mutation: 'Mutation', + subscription: 'Subscription', +}; + +/** + * Prints the SDL a Federation 1 subgraph exposes through the `_service` field: the + * type definitions without the definitions provided by the federation specification. + * + * "printSubgraphSchema" from "@apollo/subgraph" used to take care of this, but since + * v2.15 it prints the schema as-is. The `_service` field of "buildSubgraphSchema" + * also can't be used, as it now adds a stub definition for every type that is only + * extended, which "@mercuriusjs/gateway" doesn't support. + */ +export function printSubgraphSdl(typeDefs: DocumentNode): string { + const definitions = typeDefs.definitions.filter((definition) => { + if (definition.kind === Kind.DIRECTIVE_DEFINITION) { + return !FEDERATION_DIRECTIVE_NAMES.includes(definition.name.value); + } + if (definition.kind === Kind.SCHEMA_DEFINITION) { + return definition.operationTypes.some( + ({ operation, type }) => + type.name.value !== DEFAULT_ROOT_TYPE_NAMES[operation], + ); + } + return !( + 'name' in definition && + FEDERATION_TYPE_NAMES.includes(definition.name?.value) + ); + }); + return print({ ...typeDefs, definitions }); +} diff --git a/packages/mercurius/tests/e2e/code-first-federation.spec.ts b/packages/mercurius/tests/e2e/code-first-federation.spec.ts index f0575e095..5e0af65f2 100644 --- a/packages/mercurius/tests/e2e/code-first-federation.spec.ts +++ b/packages/mercurius/tests/e2e/code-first-federation.spec.ts @@ -94,9 +94,7 @@ Indicates that an object field is now resolved by this subgraph instead of anoth \"\"\" directive @override(from: String!, label: String) on FIELD_DEFINITION -type Post - @key(fields: \"id\") -{ +type Post @key(fields: \"id\") { id: ID! title: String! authorId: Int! @@ -111,10 +109,7 @@ type Query @extends { \"\"\"Search result description\"\"\" union FederationSearchResultUnion = Post | User -type User - @key(fields: \"id\") - @extends -{ +type User @key(fields: \"id\") @extends { id: ID! @external posts: [Post!]! } diff --git a/yarn.lock b/yarn.lock index ebe6604bf..75f27982f 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2,7 +2,7 @@ # yarn lockfile v1 -"@apollo/cache-control-types@^1.0.2", "@apollo/cache-control-types@^1.0.3": +"@apollo/cache-control-types@^1.0.3": version "1.0.3" resolved "https://registry.yarnpkg.com/@apollo/cache-control-types/-/cache-control-types-1.0.3.tgz#5da62cf64c3b4419dabfef4536b57a40c8ff0b47" integrity sha512-F17/vCp7QVwom9eG7ToauIKdAxpSoadsJnqIfyryLFSkLSOEqu+eC5Z3N8OXcUVStuOMcNHlyraRsA6rRICu4g== @@ -153,13 +153,13 @@ negotiator "^1.0.0" whatwg-mimetype "^4.0.0" -"@apollo/subgraph@2.14.4": - version "2.14.4" - resolved "https://registry.yarnpkg.com/@apollo/subgraph/-/subgraph-2.14.4.tgz#8b1ca90a39fb5ecde445f4ef3ee33e4701ba3f54" - integrity sha512-voALjXu3aOp2vq3LXGom2yWgG/wDmH2CMuPrZVxG/TkqcNYFzmlESC4E/XI18qfGqnvWGjMckQ2EgwRwmLaJoQ== +"@apollo/subgraph@2.15.1": + version "2.15.1" + resolved "https://registry.yarnpkg.com/@apollo/subgraph/-/subgraph-2.15.1.tgz#37c9c9d15224fee4c705673e3374b829ac7818ee" + integrity sha512-y9G5Mw5Pn/kW7u4IoyrmdFfDUe1A7s4vXYKvsqlXLO1xSYRANmVnHTRY90qGqR5Vohe79BZ/lMWDDXGsiiX+AQ== dependencies: - "@apollo/cache-control-types" "^1.0.2" - "@apollo/federation-internals" "2.14.4" + "@apollo/cache-control-types" "^1.0.3" + "@graphql-tools/utils" "^12.0.0" "@apollo/usage-reporting-protobuf@^4.1.0", "@apollo/usage-reporting-protobuf@^4.1.1": version "4.1.1" @@ -721,7 +721,7 @@ "@graphql-tools/utils" "^10.9.1" tslib "^2.4.0" -"@graphql-tools/utils@12.0.1", "@graphql-tools/utils@^12.0.1": +"@graphql-tools/utils@12.0.1", "@graphql-tools/utils@^12.0.0", "@graphql-tools/utils@^12.0.1": version "12.0.1" resolved "https://registry.yarnpkg.com/@graphql-tools/utils/-/utils-12.0.1.tgz#deb4524f776c0fd8fb695657df2d0358cacc2a49" integrity sha512-8YC6jn4xYDS6YTY6xDAgQAs/nGgvzRaIGHS8GeSfVItQzNK7Ms24CQtE3EJY+amvR+tBnhRSX0N83aGj+V/RIg==