Apollo - How to add a dynamic header for subgraph

196 views Asked by At

I am using the @apollo/gateway for a GraphQL implementation.

When implementing a subgraph, the endpoint is an internal DNS record. I have a total of 3 microservices, see below for the code snippet:

const { ApolloGateway, IntrospectAndCompose, RemoteGraphQLDataSource } = require("@apollo/gateway");

const gateway = new ApolloGateway({
    supergraphSdl: new IntrospectAndCompose({
      subgraphs: [
         { name: "users-api", url: `users.private/graphql?` },
         { name: "cars-api", url: `cars.private/graphql?` },
         { name: "posts-api", url: `posts.private/graphql?` }
      ],
    }),
    buildService({ name, url }) {
      return new RemoteGraphQLDataSource({
        url,
        willSendRequest({ request, context }) {
          Object.keys(context.headers || {}).forEach(key => {
            if (context.headers[key]) {
              request.http.headers.set(key, context.headers[key]);
            }
          });
        },
      });
    },
});

What I am trying to do is sending a custom header to each of the subgraphs. For example:

  • subgraph users-api, inject header: service=users
  • subgraph cars-api, inject header: service=cars

Is this possible?

Thanks in advance!

0

There are 0 answers