Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass request headers through to graphql resolvers

I have a graphql endpoint which is authorised by a JWT. My JWT strategy verifies the JWT then adds the user object to the request object.

In a restful route, I would access my users' data like so:

router.get('/', (req, res, next) => {
    console.log('user', req.user)
}

I want to access req.user object within my graphql resolver in order to extract the users' ID. However, when I try log the context variable, it is always empty.

Do I need to configure my graphql endpoint to pass through the req data to the resolver?

My app.js has my graphql set up like this:

import { graphqlExpress, graphiqlExpress } from 'apollo-server-express';

app.use('/graphql', [passport.authenticate('jwt', { session: false }), bodyParser.json()], graphqlExpress({ schema }));

Then I have my resolvers like so:

const resolvers = {
  Query: { 
    user: async (obj, {email}, context) => {
        console.log('obj', obj) // undefined
      console.log('email', email) // currently passed through in graphql query but I want to replace this with the user data passed in req / context
        console.log('context', context) // {}
        return await UserService.findOne(email)
    },
};

// Put together a schema
const schema = makeExecutableSchema({
  typeDefs,
  resolvers,
});

How can I access my JWT user data in my resolvers?

like image 644
Stretch0 Avatar asked Mar 07 '23 11:03

Stretch0


1 Answers

Apparently you need to pass through context manually like so:

app.use('/graphql', [auth_middleware, bodyParser.json()], (req, res) => graphqlExpress({ schema, context: req.user })(req, res) );

Found the answer here if anybody is interested:

like image 63
Stretch0 Avatar answered Mar 18 '23 00:03

Stretch0