Interagire con l'API GraphQL
Interagire con l'API GraphQLEseguire mutations in blocco

Eseguire mutations in blocco

Gato GraphQL fornisce campi di mutation « bulk » per tutte le mutations dello schema, permettendoci di mutare più risorse.

Ad esempio, la mutation createPosts (la mutation per una singola risorsa è createPost) creerà più articoli:

mutation CreatePosts {
  createPosts(inputs: [
    {
      title: "First post"
      contentAs: {
        html: "This is the content for the first post"
      }
    },
    {
      title: "Second post"
      contentAs: {
        html: "Here is another content, for another post"
      }
      excerpt: "The cup is within reach"
    },
    {
      title: "Third post"
      contentAs: {
        html: "This is yet another piece of content"
      },
      authorBy: {
        id: 1
      },
      status: draft
    }
  ]) {
    status
    errors {
      __typename
      ...on ErrorPayload {
        message
      }
    }
    post {
      id
      title
      content
      excerpt
      author {
        name
      }
      status
    }
  }
}

Argomenti

Tutte le mutations in blocco accettano due argomenti:

  • inputs (obbligatorio): l'array di elementi di input, dove ciascun elemento contiene i dati per mutare una risorsa
  • stopExecutingMutationItemsOnFirstError (predefinito false): indica se, nel caso in cui uno degli input produca un errore, l'esecuzione della mutation sugli input successivi debba essere interrotta.

Tutte le mutations vengono eseguite nello stesso ordine fornito nell'argomento inputs.

Casi d'uso

Le mutations in blocco aprono possibilità per gestire il nostro sito WordPress.

Ad esempio, la seguente query GraphQL utilizza createPosts per duplicare articoli:

query ExportPostData
{
  postsToDuplicate: posts {
    rawTitle
    rawContent
    rawExcerpt
    postInput: _echo(value: {
      title: $__rawTitle
      contentAs: {
        html: $__rawContent
      },
      excerpt: $__rawExcerpt
    })
      @export(as: "postInputs", type: LIST)
      @remove
  }
}
 
mutation CreatePosts
  @depends(on: "ExportPostData")
{
  createPosts(inputs: $postInputs) {
    status
    errors {
      __typename
      ...on ErrorPayload {
        message
      }
    }
    post {
      id
      title
      content
      excerpt
    }
  }
}