我的令牌请求查询返回null

时间:2019-04-07 01:05:36

标签: reactjs express graphql apollo-server

将令牌存储在本地存储中之后,我有一个函数,可以在验证令牌但函数返回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。

1 个答案:

答案 0 :(得分: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;
    }
  }
};