/

API Reference: @apollo/federation

Apollo Federation API reference


buildFederatedSchema

The @apollo/federation has one export for intended public use, the buildFederatedSchema function. This function is designed to take a list of GraphQL schema modules (i.e. { typeDefs: DocumentNode, resolvers: ResolverMap }) and turn them into a federation ready schema.

Parameters

  • modules: GraphQLSchemaModule[] (required)

    An array of schema modules made up of typeDefs and resolvers.

Usage

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

Though not an export from @apollo/federation, using the buildFederatedSchema function allows a resolver map to define a new special field called __resolveReference for each type that is an entity. This function is called whenever an entity is requested as part of the fufilling a query plan. __resolveReference is called with the following parameters:

Parameters

  • reference: Object

    The reference passed from another service. Will always contain at least the __typename and the primary key of the entity.

  • context: Object

    The context object generated by Apollo Server including DataSources if used.

  • info: GraphQLResolveInfo

    This argument contains information about the execution state of the query, including the field name, path to the field from the root, and more. It is currently only documented in the GraphQL.js source code.

Usage

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)
    }
  }
};
Edit on GitHub