Federation Supergraph
This example demonstrates how to consume the federation supergraph for a stitching gateway using
@graphql-tools/federation
package.
Schema Stitching is a framework or set of libraries that allows you to create gateways with a specific programmatic configuration. So it is flexible enough to consume any spec like Federation or Stitching SDL to create a gateway.
A federation supergraph SDL can be generated using Apollo Rover CLI. You can install Apollo Rover
CLI here (opens in a new tab). In our example, we create a
supergraph.yaml
file for Supergraph configuration, and use
rover supergraph compose --config ./supergraph.yaml > supergraph.graphql
to generate an SDL for
our gateway;
subgraphs:
accounts:
routing_url: http://localhost:4001/graphql
schema:
file: ./services/accounts.graphql
inventory:
routing_url: http://localhost:4002/graphql
schema:
file: ./services/inventory.graphql
products:
routing_url: http://localhost:4003/graphql
schema:
file: ./services/products.graphql
reviews:
routing_url: http://localhost:4004/graphql
schema:
file: ./services/reviews.graphql
Or you can get the supergraph sdl from a schema registry like GraphQL Hive
Sandbox
⬇️ Click ☰ to see the files
You can also see the project on GitHub here (opens in a new tab).
The following services are available for interactive queries:
- Stitched gateway: listening on 4000/graphql
- Accounts subservice_: listening on 4001/graphql
- Inventory subservice_: listening on 4002/GraphQL
- Products subservice_: listening on 4003/graphql
- Reviews subservice_: listening on 4004/graphql
This example is based on the Federation intro example (opens in a new tab).
Summary
You can use getStitchedSchemaFromSupergraphSdl
from @graphql-tools/federation
to consume a
supergraph and get an executable GraphQLSchema
that you can use with any GraphQL server or execute
it locally.
import { readFileSync } from 'fs'
import { createServer } from 'node:http'
import { createYoga } from 'graphql-yoga'
import { getStitchedSchemaFromSupergraphSdl } from '@graphql-tools/federation'
// This doesn't have to be from a file system, it can be fetched via HTTP from a schema registry
const supergraphSdl = readFileSync('./supergraph.graphql').toString()
const schema = await getStitchedSchemaFromSupergraphSdl({ supergraphSdl })
const yoga = createYoga({ schema })
const server = createServer(yoga)
server.listen(4000, () => {
console.log(`🚀 Server ready at http://localhost:4000/graphql`)
})
Subscriptions are supported without the need of any additional configuration.