如何将请求 headers 传递给 graphql 解析器

How to pass request headers through to graphql resolvers

我有一个由 JWT 授权的 graphql 端点。我的 JWT 策略验证 JWT,然后将用户 object 添加到请求 object。

在 restful 路线中,我会像这样访问我的用户数据:

router.get('/', (req, res, next) => {
    console.log('user', req.user)
}

我想在我的 graphql 解析器中访问 req.user object 以提取用户 ID。但是,当我尝试记录 context 变量时,它始终为空。

我是否需要配置我的 graphql 端点以将 req 数据传递给解析器?

我的 app.js 的 graphql 设置如下:

import { graphqlExpress, graphiqlExpress } from 'apollo-server-express';

app.use('/graphql', [passport.authenticate('jwt', { session: false }), bodyParser.json()], graphqlExpress({ schema }));

然后我有这样的解析器:

const resolvers = {
  Query: { 
    user: async (obj, {email}, context) => {
        console.log('obj', obj) // undefined
      console.log('email', email) // currently passed through in graphql query but I want to replace this with the user data passed in req / context
        console.log('context', context) // {}
        return await UserService.findOne(email)
    },
};

// Put together a schema
const schema = makeExecutableSchema({
  typeDefs,
  resolvers,
});

如何在我的解析器中访问我的 JWT 用户数据?

显然您需要像这样手动传递上下文:

app.use('/graphql', [auth_middleware, bodyParser.json()], (req, res) => graphqlExpress({ schema, context: req.user })(req, res) );

找到答案here如果有人感兴趣: