Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/apollo/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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.4",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand All @@ -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.
"""
Expand 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!]!
}
Expand Down Expand Up @@ -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",
},
}
`;
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,13 @@ export class Post {
category: Category;
}

export abstract class IQuery {
abstract getPosts(): Nullable<Nullable<Post>[]> | Promise<Nullable<Nullable<Post>[]>>;
}

export class User {
id: string;
posts?: Nullable<Nullable<Post>[]>;
}

export abstract class IQuery {
abstract getPosts(): Nullable<Nullable<Post>[]> | Promise<Nullable<Nullable<Post>[]>>;
}

type Nullable<T> = T | null;
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,13 @@ export class Post {
category: Category;
}

export abstract class IQuery {
abstract getPosts(): Nullable<Nullable<Post>[]> | Promise<Nullable<Nullable<Post>[]>>;
}

export class User {
id: string;
posts?: Nullable<Nullable<Post>[]>;
}

export abstract class IQuery {
abstract getPosts(): Nullable<Nullable<Post>[]> | Promise<Nullable<Nullable<Post>[]>>;
}

type Nullable<T> = T | null;
168 changes: 168 additions & 0 deletions packages/graphql/lib/federation/federation-directives.ts
Original file line number Diff line number Diff line change
@@ -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,
];
Original file line number Diff line number Diff line change
@@ -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<string, string> = {
query: 'Query',
mutation: 'Mutation',
subscription: 'Subscription',
};

/**
* @publicApi
*/
Expand All @@ -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,
Expand All @@ -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;
}
}
Loading