Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access the request object inside a GraphQL resolver (using Apollo-Server-Express)

I have a standard express server using GraphQL

const server = express();

server.use('/graphql', bodyParser.json(), graphqlExpress({ schema }));

Question is: how can I access the request object inside a resolver? I want to check the JWT in some specific queries

Here is the imported schema:

const typeDefs = `
    type User {
        id: String,
        name: String,
        role: Int
    }
    type Query {
        user(id: String): User,
        users: [User]
    }
`;

const resolvers = {
    Query: {
        user: (_, args, context, info) => users.find(u => u.id === args.id),
        users: (_, args, context, info) => users
    }
}

module.exports = makeExecutableSchema({typeDefs, resolvers});
like image 692
GBarroso Avatar asked Sep 09 '17 21:09

GBarroso


Video Answer


1 Answers

The request object should be accessed through the context. You can modify the options passed to your graphqlExpress middleware to define your context, like this:

server.use('/graphql', bodyParser.json(), graphqlExpress(req => ({
  schema,
  context: { user: req.user }
}))

I know express-graphql actually uses the request as the context if it's not defined in the options -- Apollo's middleware may very well behave the same way but that's unclear for the documentation.

Finally, the context is then available as the third parameter passed to your resolver function.

like image 171
Daniel Rearden Avatar answered Sep 18 '22 01:09

Daniel Rearden