【问题标题】:How to access the request object inside a GraphQL resolver (using Apollo-Server-Express)如何访问 GraphQL 解析器中的请求对象(使用 Apollo-Server-Express)
【发布时间】:2018-02-18 12:01:55
【问题描述】:

我有一个使用 GraphQL 的标准快递服务器

const server = express();

server.use('/graphql', bodyParser.json(), graphqlExpress({ schema }));

问题是:如何在解析器中访问request 对象?我想在一些特定的查询中检查 JWT

这是导入的架构:

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

【问题讨论】:

    标签: javascript express passport.js graphql graphql-js


    【解决方案1】:

    应该通过上下文访问请求对象。您可以修改传递给您的 graphqlExpress 中间件的选项来定义您的上下文,如下所示:

    server.use('/graphql', bodyParser.json(), graphqlExpress(req => ({
      schema,
      context: { user: req.user }
    }))
    

    我知道express-graphql 实际上使用请求作为上下文,如果它没有在选项中定义 - Apollo 的中间件可能会以相同的方式运行,但文档不清楚。

    最后,上下文可以作为第三个参数传递给解析器函数。

    【讨论】:

      猜你喜欢
      • 2018-03-01
      • 2018-03-12
      • 2021-07-29
      • 2019-01-11
      • 2018-08-27
      • 2020-01-28
      • 2021-07-27
      • 2020-10-01
      • 2018-10-04
      相关资源
      最近更新 更多