简体   繁体   English

处理对象数组时如何构造GraphQL突变

[英]How to structure a GraphQL mutation when dealing with an array of objects

I am using Apollo Client and trying to build a mutation that submits an object, part of that object is an array of a subtype, this array needs to be dynamic in size but I cannot find any documentation on how to correctly build this. 我正在使用Apollo Client并尝试构建一个提交对象的突变,该对象的一部分是子类型的数组,该数组的大小需要动态变化,但是我找不到任何有关如何正确构建此对象的文档。

This is my mutation with a manually typed array and this works fine. 这是我使用手动类型的数组进行的突变,效果很好。

const SET_TEMPLATE = gql`
mutation setTemplate( 
    $id: String,
    $name: String, 
    ) {
    setTemplate(
        id: $id
        input: {
            name: $name
        }
        data: [
            {
                name: "Branded"
                format: "String"
                canExpand: false
                data: {}
            },
            {
                name: "Assigned User"
                format: "String"
                canExpand: false
                data: {}
            },
            {
                name: "Assigned Users"
                format: "String"
                canExpand: false
                data: {}
            }
        ]) {
        name
        author
        data {
            name
            format
            data
        }
    }
}
`

The below is pseudo for what I want to achieve. 下面是我想要实现的伪。

const SET_TEMPLATE = gql`
mutation setTemplate( 
    $id: String,
    $name: String, 
    $data: FieldInput 
    ) {
    setTemplate(
        id: $id
        input: {
            name: $name
        }
        data: [
            $data
        ]) {
        name
        author
        data {
            name
            format
            data
        }
    }
}
`

Should I be following something like this, or is there an easier way? 我应该跟随这样的事情,还是有一种更简单的方法? Dynamic mutation document for react-apollo React-Apollo的动态突变文件

This is possible, you just have a slight problem in you mutation variable decleration. 这是可能的,您在突变变量清除中仅存在一个小问题。
Instead of $data: FieldInput declare it as $data: [FieldInput] . 代替$data: FieldInput声明为$data: [FieldInput]
The resulting query of what you'll want to achieve will look like this: 您想要实现的结果查询如下所示:

const SET_TEMPLATE = gql`
mutation setTemplate( 
    $id: String,
    $name: String, 
    $data: [FieldInput]
    ) {
    setTemplate(
        id: $id
        input: {
            name: $name
        }
        data: $data) {
        name
        author
        data {
            name
            format
            data
        }
    }
}
`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM