【问题标题】:Context within express-graphql returns a functionexpress-graphql 中的上下文返回一个函数
【发布时间】:2022-10-04 15:54:28
【问题描述】:

我正在尝试使用 express-graphql 中的上下文创建身份验证策略,但是,当我在isAuthenticated 中访问上下文时,它返回[Function: context]。我不明白什么?

app.use(
  "/graphql",
  graphqlHTTP(async (req: any) => ({
    schema: schema,
    graphiql: true,
    context: (req: any) => {
      const user = users.find((user) => user.username === "test user");

      if (!user) {
        return {
          message: "Incorrect username or password.",
        };
      }

      return {
        user: "test user",
        active: "Yes",
      };
    },
  }))
);

const isAuthenticated =
  () =>
  (next: any) =>
  async (root: any, args: any, context: any, info: any) => {
    console.log("context", context);
    if (!context.currentUser) {
      throw new Error("You are not authorized");
    }
    return next(root, args, context, info);
  };

【问题讨论】:

    标签: graphql express-graphql


    【解决方案1】:

    这是我从 Samer Buna 在他的名为“GraphQL in Action”的书中得到的建议:

    不要在 GraphQL 解析逻辑中进行身份验证。最好是 在 GraphQL 之前或之后有不同的层处理它 服务层。

    你能试试这样的吗

    server.use("/", (req, res) => {
      //currentUser logic here
    
      graphqlHTTP({
        schema: schema,
        context: { currentUser },
      })(req, res);
    });
    

    【讨论】:

      猜你喜欢
      • 2020-08-07
      • 2021-10-18
      • 1970-01-01
      • 2018-10-20
      • 1970-01-01
      • 2012-12-31
      • 2019-12-13
      • 1970-01-01
      • 2021-12-28
      相关资源
      最近更新 更多