使用React和Apollo进行GraphQL身份验证

时间:2018-01-12 15:41:43

标签: javascript reactjs authentication graphql apollo

我目前正在遵循本指南(https://www.youtube.com/watch?time_continue=1614&v=_kYUzNVyj-0)在我的react,graphql和apollo应用程序中实现身份验证。在指南中他们有这个功能:

async function context(headers, constants) {
  console.log('calling context') // This never prints, so it's not being called.
  const user = await getUser(headers['authorization'])
  return {
    headers,
    user
  }
}

在该函数下面,我得到了GraphQL的解析器和变异。其中一个查询是为了获得当前用户而看起来像这样:

export default {
  Date: GraphQLDate,
  Query: {
    currentUser: (root, args, { user }) => {
      console.log(user) // undefined 
      console.log('currentUser')
      return hello
    },
    ...

在视频中,他们稍后通过对象解构访问值,或者只是在参数中导入整个对象:

当我试图从context函数访问返回对象中的任何内容时,我得到了未定义。这是因为函数永远不会被调用,我不知道为什么。这可能是我在这里失踪的蠢事。

如果这可能有助于我的光明骑士希望能够挽救我的一天,那么我想要了解我想要工作的代码的要点。

https://gist.github.com/Martinnord/6d48132db9af1f9e7b41f1266444011c

如果有人喜欢,我可以在我的问题中添加更多上下文!非常感谢您的阅读!

1 个答案:

答案 0 :(得分:1)

您需要导出启动板的context功能才能启动它。所以

export async function context(headers, constants) {
  console.log('calling context') // This never prints, so it's not being called.
  const user = await getUser(headers['authorization'])
  return {
    headers,
    user
  }
}

IMO并不完全清楚启动板正在寻找context功能。这是一个棘手的话题,因为context函数不需要使事情有效,它不会通知你它不在那里。

相关问题