如何在两个中间件 node.js 和 apollo 服务器之间共享变量?

How to share variables between two middlewares node.js and apollo server?

我在后端使用 apollo 服务器和 graphql。

我有两个中间件,一个用于授权,另一个用于计算用户突变查询。

在 autohorization 中间件中,我正在授权当前用户并获取他的所有数据。 在计数中间件中,我正在检查查询类型并增加计数器,为此我需要在授权中间件中获取的用户 ID。

有没有优雅和简单的解决方案如何将这个 id 从一个中间件转移到另一个中间件(从授权​​到计数器)?

这是两个中间件的调用:

const apolloServerConfig = {
    schema,
    dataSources,
    context: async ({ req }) => ({ user: await autorizationMiddleware(req), counter: await counterMiddleware(req) }),
}

第一个中间件:

const { AuthenticationError } = require('apollo-server')
const AuthService = require('../auth')


module.exports = async (req) => {

    const { authorization } = req.headers



    if (!authorization) throw new AuthenticationError('not authorized')

    else {
    /......./
    
    
    return { id, email, name, lastname }
}

Conter 中间件:

module.exports = async (req) => {

    //...get id of user for further actions

        
}

这不是 graphql-middleware :) 这些只是您每次创建上下文时调用的函数。如果你想在它们之间传递信息,只需调用并等待第一个函数,然后使用 id 作为参数调用第二个函数,最后 return 你的上下文对象。

context: async ({ req }) => {
  const user = await authorizationMiddleware(req);
  const counter = await counterMiddleware(req, user.id)
  return { user, counter }
}