如何使用 apollo-server-express 从 graphql 解析器中更新会话

How to update session from within a graphql resolver using apollo-server-epxress

我有一个基于 apollo-server-express 的 graphql 服务器。

我的解析器通常对遗留 API 执行 REST 请求。 其中一个解析器通过将用户名和密码发送到后端服务器来执行用户身份验证。响应包含一个令牌,用于对后续请求进行身份验证。

目前我将令牌传递给我的客户端应用程序,将其包含在后续请求中。

我现在想将此令牌保存在 epxress-session 中,以便它可以在后续解析器的上下文中隐式传递,

但我不知道如何在解析器收到响应后更新 request.session。

首先,将会话对象包含在您的上下文中,从而将其暴露给解析器。 express-graphql 默认情况下包含请求对象作为您的上下文,但我认为 Apollo 服务器的中间件不会共享该行为——相反,我们需要显式定义上下文。

app.use('/graphql', bodyParser.json(), (req, res, next) => {
  const context = { session:req.session }
  graphqlExpress({ schema })(req, res, next)
})

然后,在您的解析器中,将返回的令牌添加到会话对象中:

const loginResolver = (obj, {username, password}, context) => {
  return apiAuthCall(username, password)
    .then(token => {
      context.session.token = token
      return // whatever other data, could just be a boolean indicated whether the login was successful
    })
}