4

My goal is to run some kind of webhook, cloud function or say I want to perform some kind of action after each query success or mutation success in graphql. Means I want to log each and every action performed by users (kind of history of when what was created and updated). How can this be implemented using some kind of middleware between graphql and DB (say mongo for now)? Means that middleware should be responsible to run the logging action each time a query or mutation is called from front-end.

Tech stack being used is- Node, express, graphQl, Redis etc.

Any suggestions would really be appreciated. Thanks

The solution I came up with was calling a function manually each time a query or mutate.

tanuj upreti
  • 123
  • 1
  • 12

1 Answers1

1

If you're using Apollo, you can utilize the formatResponse and formatError options for logging, as outlined in the docs.

const server = new ApolloServer({
  typeDefs,
  resolvers,
  formatError: error => {
    console.log(error);
    return error;
  },
  formatResponse: response => {
    console.log(response);
    return response;
  },
});

Using an extension can allow you to hook into different phases of the GraphQL request and allow more granular logging. A simple example:

const _ = require('lodash')
const { GraphQLExtension } = require('graphql-extensions')

module.exports = class LoggingExtension extends GraphQLExtension {
  requestDidStart(options) {
    logger.info('Operation: ' + options.operationName)
  }

  willSendResponse(o) {
    const errors = _.get(o, 'graphqlResponse.errors', [])
    for (const error of errors) {
      logger.error(error)
    }
  }
}

There's a more involved example here. You can then add your extension like this:

const server = new ApolloServer({
  typeDefs,
  resolvers,
  extensions: [() => new YourExtension()]
});

If you're using express-graphql to serve your endpoint, your options are a bit more limited. There's still a formatError option, but no formatResponse. There is a way to pass in an extensions array as well, but the API is different from Apollo's. You can take a look at the repo for more info.

Daniel Rearden
  • 80,636
  • 11
  • 185
  • 183
  • Logging the response is actually very simple with [express-graphql extensions](https://stackoverflow.com/a/61202468/1269037). I couldn't figure out how to [log the query](https://stackoverflow.com/questions/41142471/log-all-graphql-responses-with-express#comment108272435_41142471) though. – Dan Dascalescu Apr 14 '20 at 08:07