1

I'm new to GraphQL, and I'm now trying to make an API server with express-graphql.

What I want to do is add new property in context object for resolvers, which can be done when I initialize the express-graphql server instance.

According to the official document, it saids by default, if nothing is specified in the code, the context object in every resolver function will have an object which was previously called req in Express.js.

app.use(
  '/graphql',
  graphqlHTTP({
    schema: schema,
    graphiql: true
  })
)
// by this,
// in resolver there will be `context` available
// which includes the data previously available in `req` object (express.js case)

Then, what should I do if I want to add my own custom property in the req or context object, with all req's members altogether? I just want to add one or two new values, but not to lose other values req already has.

app.use(
  '/graphql',
  graphqlHTTP({
    schema: schema,
    graphiql: true,
    context: {
      customData: 'Yay!'
    }
  })
)
// I was able to add my own data in `context`,
// but eventually I lost all of data which was previously in the `req` object! 

Any good idea or knowledge will be very much appreciated.

cadenzah
  • 928
  • 3
  • 10
  • 23

2 Answers2

2

You can use this like that

app.use('/graphql', expressGraphql(req => ({
  schema,
  graphiql: false,
  context: {
    ...req,
    customData: 'Yay!'
  }
})))

Refer the doc https://github.com/graphql/express-graphql#providing-extensions

iAmADeveloper
  • 647
  • 3
  • 9
1

You can write a middleware to add, use it before configuring graphqlHTTP.

const setMyContext = (myContext = {}) => {
    return function (req, res, next) {
        req.myContext = myContext;
        next()
    }
};

app.use(setMyContext({
    customData: 'Yay!'
}));

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

U can access customData by

req.myContext.customData

arunp9294
  • 767
  • 5
  • 15