简体   繁体   English

如何在GraphQL解析器中访问请求对象(使用Apollo-Server-Express)

[英]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.

相关问题 错误:正文必须是字符串。 收到:{ resolvers: [[function HelloResolver]], validate: false } 使用 Type-graphql 和 apollo-server-express 时 - Error: Body must be a string. Received: { resolvers: [[function HelloResolver]], validate: false } when using Type-graphql and apollo-server-express 2022年如何使用apollo server express打开graphql游乐场页面? - How to open graphql playground page using apollo server express in 2022? 无法从 apollo-server-express 获取函数 - Cannot get functions from apollo-server-express Apollo GraphQL:如何拥有使用递归的解析器? - Apollo GraphQL: How to have a resolver that uses recursion? graphql突变如何在apollo服务器表达式中接受参数数组? - How can a graphql mutation accept an array of arguments with apollo server express? Apollo GraphQL - 未触发解析器 - Apollo GraphQL - resolver not being triggered 如何在Apollo GraphQL解析器的一个函数中解析2种不同的方法? - How to resolve 2 different methods in one function on Apollo GraphQL resolver? 如何使用 Ember-Apollo 连接到 Graphql 服务器? - How to connect to Graphql server using Ember-Apollo? 如何为GraphQL服务器设计以下解析器? - How to design the following resolver for GraphQL server? 在我的 apollo graphQL express 服务器中实现套接字连接 - Implement a socket connection in my apollo graphQL express server
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM