slicknode/graphql-query-complexity

Using this in an Apollo Gateway without `schema`

rouralberto opened this issue · 2 comments

Hi, I'm using this amazing package to control the queries in our federated ApolloGateway. The problem comes when, following the examples, I always see the schema object passed to the new ApolloServer constructor and, we don't have the schema available at Gateway level.

I would prefer to keep this cost analyser in the Gateway to avoid repeating the config in all the sub ApolloServers we have.

Is there any way to achieve this? Is there something super obvious I'm missing?

The code I'm using is:

export async function bootstrap() {
  const gateway = createApolloGateway();
  const apolloServer = new ApolloServer({
    gateway,
    plugins: [logErrorPlugin],
    introspection: (process.env.INTROSPECTION === 'true'),
    debug: (process.env.DEBUG === 'true'),
    formatError: (err) => {
    // Don't give the specific errors to the client.
    if (err.extensions.code.startsWith('DOWNSTREAM_SERVICE_ERROR')) {
      return new Error('Internal server error from subgraph ' + err.extensions.serviceName + '.  Logs are in datadog');
    }
    return err;
  },

    context: ({ req }) => {
      // Get the user token from the headers
      // Try to retrieve a user with the token
      // Add the user ID to the context
      return { req };
    },
  });
  await apolloServer.start();

  const app = express();

  configExpress(app);
  configApolloServer(apolloServer, app);

  const server = await start(app, config.port);
  attachGracefulHandlers(server);

  return { server, app };
}
ivome commented

You need the schema to run the validation. I am not that familiar with Apollo Server, but looks like you should be able to build a plugin that uses this library here:

Here you could get the schema:
https://www.apollographql.com/docs/apollo-server/integrations/plugins-event-reference/#schemadidloadorupdate

Here's a thread with some more examples that might help:
#7

Thank you @ivome for the answer. I'll keep digging to see the best way to get the schema from within a plugin. Those links helped =)