Search code examples
expressexpress-graphql

express-graphql - how can I pass res object to a custom function in context?


In my config, I have the following: -

expressGraphQL((req, res) => ({
...,
context: {
req,
res,
database,
},
}))

I would like to be able to pass res to a custom function in the context, like so: -

expressGraphQL((req, res) => ({
...,
context: {
req,
res,
database,
myCustomFunction: (res) => {
// do something with res object here
}
}))

However, when I get myCustomFunction from the context within a resolver and run is, res is undefined.

I am aware I can pull res out of the context along with myCustomFunction and invoke myCustomFunction(res) but I would like to just be able to do myCustomFunction().

Is there any way I can do this? Thanks.


Solution

  • Since you're defining the function inside of a function that is already passed res as a parameter, just use that parameter. That means you should remove the res argument from myCustomFunction's signature, otherwise you end up shadowing the res variable you actually mean to use.

    expressGraphQL((req, res) => ({
      ...,
      context: {
        ...
        myCustomFunction: () => {
          console.log(res)
        },
      },
    }))
    

    You can define myCustomFunction in a different scope too, in which case you would do:

    function myCustomFunction (res) {
      console.log(res)
    }
    
    expressGraphQL((req, res) => ({
      ...,
      context: {
        ...
        myCustomFunction: () => myCustomFunction(res),
      },
    }))