1

I'm using express-graphql in my nodejs app.

In order to get access to the database from the resolvers, I have created an object called ProjectHandler (which handles a table in the database called projects) and I'm injecting it to the resolvers by changing the context when creating the express-graphql instance, like so:

app.use('/graphql', graphqlHTTP({
  schema,
  graphiql: true,
  context: {projectsHandler}
}))

problem is, this replaces the default context from being a representation of the request object, preventing me from accessing session information.

The thing is, that I need both the session information and the project handler. How do I do that?

Tom Klino
  • 2,358
  • 5
  • 35
  • 60

1 Answers1

2

graphqlHTTP function returns an express middleware so in order to pass a custom context with the request object in it we'll have to wrap that function with our own middleware, and activate the graphqlHTTP middleware

this code below should work (haven't tried tough):

 app.use('/graphql', (request, response) => {
     return graphqlHTTP({
        schema,
        graphiql: true,
        context: {
            projectsHandler,
            request
        }
     })(request, response);
 })
  • 1
    It does :) I actually solved it 2 hours ago exactly like that! (the last parentases - calling the function - are actually not necessary though, just having the options argument as a function is suffice, it's being called every request by express-graphql) – Tom Klino Aug 04 '18 at 10:54