【问题标题】:How to resolve GraphQl mutations that have an array as the input如何解决以数组为输入的 GraphQl 突变
【发布时间】:2020-05-13 03:41:42
【问题描述】:

所以是 GraphQL 的新手,我正在尝试解决具有数组输入类型的突变。我收到此错误

{
  "data": {
    "createSub": null
  },
  "errors": [
    {
      "message": "Variable '$data' expected value of type 'SubCreateInput!' but got: {\"apps\":[{\"name\":\"ma\",\"package\":\"me\",\"running\":true,\"isSysytem\":true}]}. Reason: 'apps' Expected 'AppListCreateManyInput', found not an object. (line 1, column 11):\nmutation ($data: SubCreateInput!) {\n          ^",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "createSub"
      ]
    }
  ]
}

这是我的架构

type Mutation {
    createSub(input:subInput): Sub  
  }

input subInput{

    apps: [AppListInput]
}

type Sub{
    id: ID!
    apps: [AppList]  
  }


type AppList {
    id: ID!
    name: String
    package: String
    running: Boolean
    isSysytem: Boolean

}

input AppListInput {
    name: String
    package: String
    running: Boolean
    isSysytem: Boolean

  }

这是我的解析器

function createSub(root, args, context) {
    return context.prisma.createSub({
      apps: args.input.apps
    })
  }

在 Graphql 操场上发送的突变/有效负载是这样的

mutation{
    createSub( input:{
      apps: [{
        name: "ma"
        package: "me"
        running: true
        isSysytem: true

      }],
    })
  {
    apps{
      name
    }
  }
  }

当我 console.log(args.input.apps) 我得到这个

[ [Object: null prototype] { name: 'ma', package: 'me', running: true, isSysytem: true } ]

这是模式中生成的输入AppListCreateManyInput

input AppListCreateManyInput {
  create: [AppListCreateInput!]
  connect: [AppListWhereUniqueInput!]
}

请问我会遗漏什么?

【问题讨论】:

  • 在浏览器中刷新 Playground,或者尝试重新编译你的输入。看起来它们与您在此处提供的内容已过时。 Reason: 'apps' Expected 'AppListCreateManyInput', 类型 AppListCreateManyInput 不是您提供的内容的一部分,查询也不是代码示例的一部分。 (例如:$data' expected value of type 'SubCreateInput 突变 SubCreateInput 和变量名 data 不是您的示例代码的一部分)否则,从我所看到的情况来看,您的代码示例似乎是在正确的轨道上。
  • @jmunsch 我尝试过重新编译我的类型。我什至创建了一个新的数据库实例并重新编写了我的模型,但错误仍然存​​在。
  • @jmunsch 至于像 AppListCreateManyInputSubCreateInput 这样的类型/输入,它们是由 Prisma 在模式中生成的
  • 您传入的apps 应该是一个对象,而不是一个数组,如错误所示。查看生成的模式文件中AppListCreateManyInput 的定义,以查看该对象应该是什么形状。如果您仍然不确定,请使用架构文件中的定义更新您的问题。
  • @DanielRearden 即使将 apps 作为对象传入,我也会遇到同样的错误。我已更新问题以包含架构中的 AppListCreateManyInput

标签: node.js graphql graphql-js prisma-graphql


【解决方案1】:

您需要向createSub 提供适当的对象,如图here。因为apps是一个关系,你不能只传递apps的数组——毕竟,在创建Sub时,你可能想要创建新的应用程序并将它们与新创建的Sub相关联,或者只是将现有应用与它相关联。

return context.prisma.createSub({
  apps: {
    create: args.input.apps, // create takes an array of apps to create
  }
})

如果您想连接现有应用而不是创建新应用,您可以使用 connect 而不是 create 并传入一个指定 where 条件的对象而不是数组。

【讨论】:

    猜你喜欢
    • 2019-08-15
    • 2021-06-13
    • 2019-01-25
    • 2019-03-09
    • 2020-05-18
    • 2016-08-15
    • 2020-11-02
    • 2021-02-27
    • 2021-04-14
    相关资源
    最近更新 更多