GBarroso
GBarroso

Reputation: 477

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

Upvotes: 6

Views: 5910

Answers (1)

Daniel Rearden
Daniel Rearden

Reputation: 84687

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.

Upvotes: 13

Related Questions