4

I have a question about express-graphql. I’m trying to get a middleware run after the GraphQL resolver.

These were my first two attempts:

app.use('/api', graphqlHTTP({
    schema: graphqlSchema
  })
);

app.use((req, res, next) => {
  console.log('middleware called');
  next();
});

and

app.use('/api', graphqlHTTP({
    schema: graphqlSchema,
    graphiql: true,
  }), () => {
      console.log('middleware called');
  }
);

Both aren’t working. I guess express-graphql is not calling next() somewhere.

The source seems to confirm this:

type Middleware = (request: Request, response: Response) => void;

next is not a parameter.

I tried this workaround:

app.use( (req, res, next) => {
  req.on('end', () => {
    console.log('middleware called');
  });
  next();
});

app.use('/api', graphqlHTTP({
    schema: graphqlSchema
  })
);

It kind of works. But in real usage I noticed, that data changed by mutations is not yet available (i. e. already updated) in the callback. If I wrap the code inside a setTimeout the data is updated.

Bottom line: how I can get middleware (or any code) to run after the resolver?

zagen
  • 41
  • 1
  • 4

0 Answers0