首页 > 解决方案 > 如何将参数传递给 graphqlHTTP 中间件

问题描述

我如何将参数传递给 graphqlHTTP 中间件

我正在尝试将授权标头令牌有效负载从另一个上层中间件传递给 graphqlHTTP 中间件

app.use('/private', (req:Request,res:Response,next:Function) => {

   if(!req.header('Authorization')){
      res.json({
         error:true,
         message:'Authorization bearer required'
      })
   }else{
      const token = Buffer.from(req.header('Authorization').split('Bearer ')[1], 'base64').toString('ascii');
      if(decode(token)){
         next();
      }else{
         res.json({
            error:true,
            message:'Authorization bearer required'
         })
      }
   }
});

app.use('/private', graphqlHTTP({
   schema:privateSchema,
   graphiql:false
}))

标签: node.jsexpressgraphql-js

解决方案


在请求本身中从中间件设置数据是很常见的。

在您的场景中,可以将令牌设置为req.token然后传递给您的 graphql 解析器上下文,例如:

// main.js

app.use(authMidddleware) // sets req.token
app.use(
  '/graphql',
  bodyParser.json(),
  graphqlExpress(req => ({ schema, context: req }))
)

// some-resolver.js
export const myResolver = {
  Query: {
    token: async (parent, { input }, context) => {
      const { token } = context;
      // other stuff
    }
  }
}

推荐阅读