【问题标题】:FakeData "Error: Cannot return null for non-nullable field"FakeData“错误:不能为不可为空的字段返回空值”
【发布时间】:2021-12-09 06:31:20
【问题描述】:

我制作了我的第一个 apollo 服务器来尝试理解它,到目前为止,我正在使用我创建的数组对其进行测试,并使用 graphQL 游乐场测试我的突变。

我的数据是一个大数组 像这样:

const lists = [
    {
      id: 'list-0',
      name: 'Example 1',
      tasks: [{name:"task1", id:"1", completed: false},{name:"task2", id:"2", completed: true}, ]
      },
    {
      id: 'list-1',
      name: 'Example 2',
      tasks: [{name:"task1", id:"1", completed: false},{name:"task2", id:"2", completed: true}, ]
    },
  ];

到目前为止,我能够添加列表名称、删除列表并通过 id 获取列表。我想做的是,将一个新的任务对象添加到列表中。

我的变异和类型是这样的:

type Task {
  id: String!
  name: String!
  completed: Boolean!
}

type List {
  id: String!
  name: String!
  tasks: [Task!]!
}

addTask(listId: String!, name: String!): Task!

我为解析器创建的函数 addTask 是这样的:


        addTask(parents, {listId, name}) {
            const newTask = lists.map((list) => {
              if (listId === list.id) {
                return {
                  ...list,
                tasks: [...list.tasks, { name, completed: false, id:"eaz"}],
              };
            }
            console.log("test1", list)
            return list
            })
            console.log("test2", newTask)
            return newTask
          },

当我使用 graphQL 操场时,我将我的 list.id 之一作为下面的目标,但控制台日志告诉我任务:[ [Object], [Object] ] 并且 graphQL 操场带来告诉我任务为空。

mutation Mutation {
  addTask(listId: "task-0", name: "eze") {
    name
  }
}

我是否缺少有关 graphQL 的内容?我应该将数组任务和列表分开吗? 感谢阅读。

【问题讨论】:

    标签: graphql apollo-server


    【解决方案1】:

    在您的控制台日志中,newTask 如下所示:

    [ [Object], [Object] ]
    

    它是一个数组,而不是一个对象,[].name 是undefined,它被转换为null。

    根据您的类型定义,您必须返回具有此结构的对象:

    type Task {
      id: String!
      name: String!
      completed: Boolean!
    }
    

    如果相反,你的代码做了这样的事情,我认为它会给你想要你说它正在返回:

      addTask(parents, { listId, name }) {
        let newTask
        lists.forEach((list) => {
          if (listId === list.id) {
            newTask = { name, completed: false, id: 'eaz' }
            list.tasks.push(newTask)
          }
          console.log('test1', list)
          return list
        })
        console.log('test2', newTask)
        return newTask
      }
    

    这里的newTask是对象{ name, completed: false, id: 'eaz' }


    额外积分:

    .map 或 .forEach 的替代方案,它循环遍历每个项目,无论做什么,您都可以做一些更高效的事情,比如

      addTask(parents, { listId, name }) {
        const newTask = { name, completed: false, id: 'eaz' }
        const list = lists.find((list) => {
          return listId === list.id
        }
        if (!list) throw new Error('listId not found')
        list.tasks.push(newTask)
        console.log('test1', list)
        console.log('test2', newTask)
        return newTask
      }
    

    【讨论】:

      猜你喜欢
      • 2023-02-18
      • 1970-01-01
      • 2019-05-28
      • 2020-09-24
      • 2020-11-16
      • 2021-08-06
      • 2021-05-11
      • 2021-07-01
      • 2019-10-25
      相关资源
      最近更新 更多