Express-graphql: [RFC] Allow a function for the context

Created on 19 Jan 2017  路  4Comments  路  Source: graphql/express-graphql

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.

Most helpful comment

@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
  }
})));

All 4 comments

@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
  }
})));

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

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

context is object , can allow context with a function

Was this page helpful?
0 / 5 - 0 ratings

Related issues

violet-day picture violet-day  路  3Comments

phuchle2 picture phuchle2  路  3Comments

stevvvn picture stevvvn  路  3Comments

brunolemos picture brunolemos  路  5Comments

arealmaas picture arealmaas  路  4Comments