Apollo Federation subgraph utilities for the graphql-js ecosystem.
@apollo/subgraph is built on top of graphql-js and provides transformation logic
to make your GraphQL schemas Federation compatible. buildSubgraphSchema adds common
Federation type definition (e.g. Any scalar, _Entity union, Federation directives,
etc) and allows you to easily specify your Federated entity resolvers.
Requires Node.js 22 or later.
npm install @apollo/subgraph graphqlimport { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';
import { buildSubgraphSchema } from '@apollo/subgraph';
import gql from 'graphql-tag';
const typeDefs = gql`
extend schema
@link(url: "https://specs.apollo.dev/federation/v2.9", import: ["@key"])
type Query {
product(id: ID!): Product
}
type Product @key(fields: "id") {
id: ID!
name: String
}
`;
const resolvers = {
Query: {
product: (_source, { id }) => products.find((product) => product.id === id),
},
Product: {
// Called for each entity representation the router sends to `_entities`.
__resolveReference: (reference) =>
products.find((product) => product.id === reference.id),
},
};
const server = new ApolloServer({
schema: buildSubgraphSchema([{ typeDefs, resolvers }]),
});
await startStandaloneServer(server, { listen: { port: 4001 } });buildSubgraphSchema(modulesOrSDL)— builds the executable subgraph schema. Accepts aDocumentNode, or an array of documents or{ typeDefs, resolvers }modules.printSubgraphSchema(schema)— prints the complete subgraph schema, federation directives and types included.addResolversToSchema(schema, resolvers)— attaches a resolver map to an existing schema, understanding__resolveReferencealongside the usual__resolveType/__isTypeOf.entitiesResolver({ representations, context, info })— the_entitiesresolver, exported for libraries that assemble their own root fields.
Entity references are resolved through __resolveReference, either from a
resolver map or from extensions.apollo.subgraph.resolveReference on the type.
npm install
npm run build
npm testThe compatibility/ workspace runs the
Apollo Federation subgraph compatibility suite
against this library, using docker compose for the router and reference subgraphs.
See its README.
npm run compatibility --workspace @apollo/subgraph-compatibilityIf you have a specific question about the library or code, please start a discussion in the Apollo community forums.
See CONTRIBUTING.md for details.
After you have your local branch set up, take a look at our open issues to see where you can contribute.
For more info on how to contact the team for security issues, see our Security Policy.
This library is licensed under The MIT License (MIT).