API Reference: @apollo/federation
Apollo Federation API reference
This API reference documents the exports from the @apollo/federation
package.
buildFederatedSchema
A function that takes an array of GraphQL schema modules and returns a federation-ready schema based on those modules:
const server = new ApolloServer({
schema: buildFederatedSchema([{ typeDefs, resolvers }])});
Used when defining a subgraph in a federated graph.
Each schema module is an object with the following format:
{
typeDefs: DocumentNode,
resolvers: ResolverMap
}
Parameters
Name / Type | Description |
---|---|
| Required. An array of schema module objects with the structure shown above. |
Example
const typeDefs = gql`
type Query {
me: User
}
type User @key(fields: "id") {
id: ID!
username: String
}
`;
const resolvers = {
Query: {
me() {
return { id: "1", username: "@ava" }
}
},
User: {
__resolveReference(user, { fetchUserById }){
return fetchUserById(user.id)
}
}
};
const server = new ApolloServer({
schema: buildFederatedSchema([{ typeDefs, resolvers }])
});
__resolveReference
The name of a special reference resolver function you can define for every entity in a resolver map, if that resolver map is part of a federated schema.
The __resolveReference
function enables your gateway's query planner to resolve a particular entity by whatever unique identifier your other subgraphs use to reference it. For details, see Entities: Resolving.
The function takes the parameters listed below.
Parameters
Name / Type | Description |
---|---|
| The representation of the entity that's passed from another subgraph. This object includes a |
| An object that's passed to every resolver that executes for a particular operation. This enables resolvers to share helpful context, including any relevant For details, see The |
| Contains information about the operation's execution state, including the field name, the path to the field from the root, and more. This object's core fields are listed in the GraphQL.js source code, and it is extended with additional functionality by other modules, like |
Example
const typeDefs = gql`
type User @key(fields: "id") {
id: ID!
username: String
}
`;
const resolvers = {
User: {
__resolveReference(user, { datasources }){
// user will always have at least the `id` and the `__typename` here
return datasources.users.fetchUserById(user.id)
}
}
};