[英]How to access the request object inside a GraphQL resolver (using Apollo-Server-Express)
I have a standard express server using GraphQL 我有一个使用GraphQL的标准快递服务器
const server = express();
server.use('/graphql', bodyParser.json(), graphqlExpress({ schema }));
Question is: how can I access the request
object inside a resolver? 问题是:如何在解析器中访问
request
对象? I want to check the JWT in some specific queries 我想在一些特定的查询中检查JWT
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:
您可以修改传递给graphqlExpress中间件的选项来定义您的上下文,如下所示:
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. 我知道
express-graphql
实际上使用请求作为上下文,如果它没有在选项中定义 - Apollo的中间件可能表现得很好但文档不清楚。
Finally, the context is then available as the third parameter passed to your resolver function. 最后,上下文可用作传递给解析器函数的第三个参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.