GraphQL
Beginner
1 min read
Apollo Federation: Building a Supergraph
Example
// users-subgraph/schema.graphql
extend schema @link(url: "https://specs.apollo.dev/federation/v2.0", import: ["@key"])
type User @key(fields: "id") {
id: ID!
name: String!
email: String!
}
type Query {
user(id: ID!): User
me: User
}
// orders-subgraph/schema.graphql — extends User from users-subgraph
extend schema @link(url: "https://specs.apollo.dev/federation/v2.0", import: ["@key", "@external"])
type User @key(fields: "id") {
id: ID! @external # owned by users-subgraph
orders: [Order!]! # added by this subgraph
}
type Order {
id: ID!
total: Float!
status: String!
}
type Query {
order(id: ID!): Order
}
// orders-subgraph/resolvers.js
const resolvers = {
User: {
// Federation calls this to load user's orders
orders: (user) => db.orders.findAll({ userId: user.id }),
// Reference resolver: reconstitute User from { id }
__resolveReference: (ref) => ({ id: ref.id }),
},
};
// Apollo Router config (router.yaml):
// supergraph:
// listen: 0.0.0.0:4000
// subgraphs:
// users: { routing_url: http://users-service:4001/graphql }
// orders: { routing_url: http://orders-service:4002/graphql }
Related Resources
GraphQL Reference
Complete tag & property list
GraphQL How-To Guides
Step-by-step practical guides
GraphQL Exercises
Practice what you've learned
More in GraphQL
This is the last lesson in this section.
Create a free account to earn a certificate