DEV Community

Cover image for Best way to glue Graphql APIs with Apollo Federation
Tommaso De Rossi
Tommaso De Rossi

Posted on

Best way to glue Graphql APIs with Apollo Federation

Apollo federation is sure the best way to glue together many graphql services, to add support for apollo federation is super easy:

const { ApolloServer, gql } = require("apollo-server");
const { buildFederatedSchema } = require("@apollo/federation");

const typeDefs = gql`
  ...
`;

const server = new ApolloServer({
  schema: buildFederatedSchema([
    {
      typeDefs,
      resolvers: {
        Query: {
          // ...
        },
      }
    }
  ])
});

server.listen({ port: 80 }).then(({ url }) => {
  console.log(`๐Ÿš€ Server ready at ${url}`);
});

The server above can then be integrated in a gateway using apollo server with many other related services, the Query and Mutation types will be merged and the types with same name will be glued together in the unified schema gateway.

But how should i create this gateway?
You could write one yourself using the @apollo/gateway npm library only to find out that you should also handle the forwarding of headers and restart the service when other services schema changes.

Well you don't need to waste your time because i already wasted mine just for you.
You can use my reusable docker image with docker-compose as follows:


version: '3'

services:
    a:
        build: ./a # one service implementing federation
    b:
        build: ./b
    gateway:
        image: xmorse/apollo-federation-gateway
        ports:
            - 8000:80
        environment: 
            CACHE_MAX_AGE: '5' # default cache
            ENGINE_API_KEY: '...' # to connect to the apollo engine
            POLL_INTERVAL: 30 # to update services changes
            URL_0: "http://a"
            URL_1: "http://b"
            # you can also add other services outside docker

Please star the github repo if you are using the image so i can fulfil my pathological stars thirst.

Top comments (0)