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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With