我的令牌查询请求返回null

问题描述 投票:0回答:1

令牌存储在本地存储中之后,我有一个函数,我可以在验证令牌但是函数返回null时加载currentStudent的数据。

这是我的解析器代码

  getCurrentStudent: async (
      root,
      { studentId },
      { currentStudent, Student }
    ) => {
      if (!currentStudent) {
        return null;
      }
      const student = await Student.findOne({
        studentId: currentStudent.studentId
      });
      return student;
    }

然后我尝试用ApolloServer实例创建一个上下文

const server = new ApolloServer({
  typeDefs,
  resolvers,
  context: async ({ req }) => {
    const token = req.headers["authorization"];
    if (token !== null) {
      try {
        const currentStudent = await jwt.verify(token, process.env.SECRET);
        req.currentStudent = currentStudent;
      } catch (err) {
        console.log(err);
      }
    }
  }
});

这应该验证我的令牌并返回currentUser。

reactjs express graphql apollo-server
1个回答
0
投票

传递给上下文的函数应该返回一个上下文对象,或者一个将解析为一个的Promise:

context: async ({ req }) => {
  const token = req.headers["authorization"];
  let currentStudent;
  if (token !== null) {
    try {
      const currentStudent = await jwt.verify(token, process.env.SECRET);
      currentStudent = currentStudent;
    } catch (err) {
      console.log(err);
    }
  }
  return {
    currentStudent,
  };
}

然后,您可以在任何解析器中使用该上下文,例如:

const resolvers = {
  Query: {
    currentStudent: (root, args, context) => {
      return context.currentStudent;
    }
  }
};
© www.soinside.com 2019 - 2024. All rights reserved.