【问题标题】:How to write a GraphQL update mutation for sql db (Apollo Server)如何为 sql db (Apollo Server) 编写 GraphQL 更新突变
【发布时间】:2023-03-05 12:16:01
【问题描述】:

我正在尝试为我的前端编写一个更新突变。

这就是我所拥有的 解析器:

    async updateUser(root, { id, name, email, password }, { models }) {
      return models.User.update(
        {
          id,
          name,
          email,
          password
        },
        {
          where: { id: id }
        }
      );
    }
  }

架构:

    updateUser(
      id: Int!
      name: String!
      email: String!
      password: String!
    ): User!

在前端调用这个会返回一个错误:“Cannot return null for non-nullable field User.id.”- 然后在页面刷新后,变化就反映了。

这就是我在前端所说的:

          updateUser({
            variables: {
              id: props.item.id,
              name: changeText,
              email: props.item.email,
              password: "password"
            }
          });

我相信我不会以正确的方式返回它的突变。谢谢。

【问题讨论】:

  • models.User.update 返回什么?一些 ORM 返回一个布尔值以指示 INSERT/UPDATE 操作成功,而其他 ORM 实际上返回变异的记录。您需要确保 models.User.update 的结果以 GraphQL 期望的形状和类型返回数据。
  • 在我的模式中,它返回一个用户,就像我的创建突变一样工作正常。由于某种原因,更新程序不返回任何内容。上面添加了架构。

标签: sql graphql apollo


【解决方案1】:

我通过等待更改然后显式返回参数来解决它。

 async updateUser(root, { id, name, email, password }, { models }) {
      await models.User.update(
        {
          id,
          name,
          email,
          password
        },
        {
          where: { id: id }
        }
      );
      return { id, name, email, password }
    }

【讨论】:

    猜你喜欢
    • 2019-08-29
    • 2021-03-24
    • 2020-10-20
    • 2021-03-03
    • 2020-04-24
    • 2018-09-05
    • 2020-02-28
    • 2021-04-14
    • 2021-08-23
    相关资源
    最近更新 更多