graphql / express-graphql

Create a GraphQL HTTP server with Express.
MIT License
6.34k stars 538 forks source link

[RFC] Allow a function for the context #187

Closed arunoda closed 7 years ago

arunoda commented 7 years ago

If we don't set a context, express-graphql set the http request object as the context. If we provide a context explicitly, there's no way we could access the HTTP request object inside a resolve function.

So, here's my suggestion. We could pass a function for the context. It's a mapper and it receives the request object as the first argument.

See:

app.use('/graphql', expressGraphql({
  schema,
  graphiql: true,
  context (req) {
    return {
      user: req.user,
      db: appInfo.db
    }
  }
}))

May be this is a breaking change if someone already passing a function for context. If so, we could do this with a different field like contextMapper.

nodkz commented 7 years ago

@arunoda, right now you may do it in such way:

app.use('/graphql', expressGraphql((req) => ({
  schema,
  graphiql: false
  context: {
    user: req.user,
    db: appInfo.db
  }
})));
arunoda commented 7 years ago

Thanks @nodkz. That's pretty cool. I totally miss this part in the README: https://github.com/graphql/express-graphql#providing-extensions

venkat4541 commented 6 years ago

Where is the context object used? And how? Trying to understand a use case.

longvd89 commented 5 years ago

context is object , can allow context with a function