简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM