简体   繁体   中英

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.

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

This is possible, you just have a slight problem in you mutation variable decleration.
Instead of $data: FieldInput declare it as $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
        }
    }
}
`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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