Tutorial del esquema
Tutorial del esquemaLección 4: Duplicar varias entradas de blog a la vez

Lección 4: Duplicar varias entradas de blog a la vez

Podemos extender la lección anterior del tutorial para duplicar varias entradas con una sola petición GraphQL.

Consulta GraphQL para duplicar varias entradas a la vez

Para que esta consulta GraphQL funcione, la Creando una configuración del esquema aplicada al endpoint debe tener habilitadas las Usar mutaciones anidadas

Esta consulta GraphQL duplica las entradas recuperadas mediante las variables $limit y $offset proporcionadas:

query InitializeDynamicVariables
  @configureWarningsOnExportingDuplicateVariable(enabled: false)
{
  postInputs: _echo(value: [])
    @export(as: "postInputs")
    @remove
}
 
query GetPostsAndExportData($limit: Int! = 5, $offset: Int! = 0)
  @depends(on: "InitializeDynamicVariables")
{
  postsToDuplicate: posts(
    pagination: {
      limit : $limit
      offset: $offset
    }
    sort: {
      by: ID,
      order: ASC
    }
  ) {
    # Fields not to be duplicated
    id
    slug
    date
    status
 
    # Fields to be duplicated
    author {
      id
    }
    categories {
      id
    }
    rawContent
    excerpt
    featuredImage {
      id
    }
    tags {
      id
    }
    title
 
    # Already create (and export) the inputs for the mutation
    postInputs: _echo(value: {
      status: draft,
      authorBy: {
        id: $__author
      },
      categoriesBy: {
        ids: $__categories
      },
      contentAs: {
        html: $__rawContent
      },
      excerpt: $__excerpt
      featuredImageBy: {
        id: $__featuredImage
      },
      tagsBy: {
        ids: $__tags
      },
      title: $__title
    })
      @export(as: "postInputs", type: LIST)
      @remove
  }
}
 
mutation DuplicatePosts
  @depends(on: "GetPostsAndExportData")
{
  createPosts(inputs: $postInputs) {
    status
    errors {
      __typename
      ...on ErrorPayload {
        message
      }
    }
    post {
      # Fields not to be duplicated
      id
      slug
      date
      status
 
      # Fields to be duplicated
      author {
        id
      }
      categories {
        id
      }
      rawContent
      excerpt
      featuredImage {
        id
      }
      tags {
        id
      }
      title
    }
  }
}

Paso a paso: creación de la consulta GraphQL

A continuación se muestra el análisis detallado de cómo funciona la consulta.

Ampliando la lección "Duplicar una entrada de blog"

La lección anterior emplea la siguiente estrategia (en la consulta GraphQL del segundo enfoque):

  1. Exportar los IDs de los recursos desde los campos (incluyendo los campos de conexión):
query GetPostAndExportData {
  post {
    author @export(as: "authorID") {
      id
    }
    categories @export(as: "categoryIDs") {
      id
    }
    rawContent @export(as: "rawContent")
    rawExcerpt @export(as: "excerpt")
    featuredImage @export(as: "featuredImageID") {
      id 
    }
    tags @export(as: "tagIDs") {
      id
    }
    rawTitle @export(as: "title")    
  }
}
  1. Crear el objeto input para createPost(input:) a partir de esas variables dinámicas:
mutation DuplicatePost
  @depends(on: "GetPostAndExportData")
{
  createPost(input: {
    status: draft,
    authorBy: {
      id: $authorID
    },
    categoriesBy: {
      ids: $categoryIDs
    },
    contentAs: {
      html: $rawContent
    },
    excerpt: $excerpt
    featuredImageBy: {
      id: $featuredImageID
    },
    tagsBy: {
      ids: $tagIDs
    },
    title: $title
  }) {
    # ...
  }
}

Gracias a la extensión Field To Input podemos crear el objeto input ya en la primera operación y exportar todos los datos requeridos de la entrada bajo una única variable dinámica:

query GetPostAndExportData {
  post {
    author {
      id
    }
    categories {
      id
    }
    rawContent
    excerpt
    featuredImage {
      id
    }
    tags {
      id
    }
    title
 
    postInputs: _echo(value: {
      status: draft,
      authorBy: {
        id: $__author
      },
      categoriesBy: {
        ids: $__categories
      },
      contentAs: {
        html: $__rawContent
      },
      excerpt: $__excerpt
      featuredImageBy: {
        id: $__featuredImage
      },
      tagsBy: {
        ids: $__tags
      },
      title: $__title
    })
      @export(as: "postInputs")
  }
}

Entonces, en la siguiente mutación, createPost(input:) recibe directamente la variable dinámica $postInputs:

mutation DuplicatePost
  @depends(on: "GetPostAndExportData")
{
  createPost(input: $postInputs) {
    # ...
  }
}

Obtener varias entradas

Debemos convertir la consulta para obtener las varias entradas a duplicar:

  • Consultar las entradas mediante posts(pagination: { limit : $limit, offset: $offset}) { ... }
  • Exportar postInputs como una lista (es decir, un array que contiene todos los inputs de las entradas consultadas)
query GetPostsAndExportData($limit: Int! = 5, $offset: Int! = 0)
  @depends(on: "InitializeDynamicVariables")
{
  postsToDuplicate: posts(
    pagination: {
      limit : $limit
      offset: $offset
    }
    sort: {
      by: ID,
      order: ASC
    }
  ) {
    # ...
 
    postInputs: _echo(value: {
      # ...
    })
      @export(
        as: "postInputs",
        type: LIST
      )
  }
}

Crear varias entradas en una sola consulta GraphQL

A estas alturas, la variable dinámica $postInputs contiene un array con todos los datos de entrada para cada una de las entradas a duplicar:

[
  {
    "status": "draft",
    "authorBy": {
      "id": "2"
    },
    "categoryIDs": [
      1
    ],
    "contentAs": {
      "html": "<!-- wp:paragraph -->\n<p>Welcome to WordPress. This is your first post. Edit or delete it, then start writing!</p>\n<!-- /wp:paragraph -->"
    },
    "excerpt": "Welcome to WordPress. This is your first post. Edit or delete it, then start writing!",
    "featuredImageBy": {
      "id": null
    },
    "tagsBy": {
      "ids": []
    },
    "title": "Hello world!"
  },
  {
    "status": "draft",
    "authorBy": {
      "id": "3"
    },
    "categoryIDs": [
      3
    ],
    "contentAs": {
      "html": "<!-- wp:paragraph -->\n<p>This is a paragraph block. Professionally productize highly efficient results with world-class core competencies. Objectively matrix leveraged architectures vis-a-vis error-free applications. Completely maximize customized portals via fully researched metrics. Enthusiastically generate premier action items through web-enabled e-markets. Efficiently parallel task holistic intellectual capital and client-centric markets.<br><br></p>\n<!-- /wp:paragraph -->\n\n<!-- wp:heading -->\n<h2>Image Block (Standard)</h2>\n<!-- /wp:heading -->\n\n<!-- wp:image {\"id\":1755} -->\n<figure class=\"wp-block-image\"><img src=\"https://d.pr/i/8pTmgY+\" alt=\"\" class=\"wp-image-1755\"/></figure>\n<!-- /wp:image -->"
    },
    "excerpt": "This is a paragraph block. Professionally productize highly efficient results with world-class core competencies. Objectively matrix leveraged architectures vis-a-vis error-free applications. Completely maximize customized portals via fully researched metrics. Enthusiastically generate premier action items through web-enabled e-markets. Efficiently parallel task holistic intellectual capital and client-centric markets. Image Block (Standard)",
    "featuredImageBy": {
      "id": 361
    },
    "tagsBy": {
      "ids": [
        11,
        10
      ]
    },
    "title": "Released v0.6, check it out"
  }
]

Finalmente, llamamos a la mutación en bloque createPosts para crear todas las entradas pasando los datos de los inputs exportados:

mutation DuplicatePosts
  @depends(on: "GetPostsAndExportData")
{
  createPosts(inputs: $postInputs) {
    status
    errors {
      __typename
      ...on ErrorPayload {
        message
      }
    }
    post {
      # Fields not to be duplicated
      id
      slug
      date
      status
 
      # Fields to be duplicated
      author {
        id
      }
      categories {
        id
      }
      rawContent
      excerpt
      featuredImage {
        id
      }
      tags {
        id
      }
      title
    }
  }
}

Finalmente, llamamos a la mutación en bloque createPosts para crear todas las entradas pasando todos los inputs:

mutation DuplicatePosts
  @depends(on: "GetPostsAndExportData")
{
  createPosts(inputs: $postInputs) {
    status
    errors {
      __typename
      ...on ErrorPayload {
        message
      }
    }
    post {
      # Fields not to be duplicated
      id
      slug
      date
      status
 
      # Fields to be duplicated
      author {
        id
      }
      categories {
        id
      }
      rawContent
      excerpt
      featuredImage {
        id
      }
      tags {
        id
      }
      title
    }
  }
}

Eliminar datos innecesarios

El paso final es eliminar mediante @remove todos los campos que son auxiliares (y como tal no necesitamos imprimir su salida en la respuesta).

La consulta GraphQL consolidada es:

query InitializeDynamicVariables
  @configureWarningsOnExportingDuplicateVariable(enabled: false)
{
  postInputs: _echo(value: [])
    @export(as: "postInputs")
    @remove
}
 
query GetPostsAndExportData($limit: Int! = 5, $offset: Int! = 0)
  @depends(on: "InitializeDynamicVariables")
{
  postsToDuplicate: posts(
    pagination: {
      limit : $limit
      offset: $offset
    }
    sort: {
      by: ID,
      order: ASC
    }
  ) {
    # Fields not to be duplicated
    id
    slug
    date
    status
 
    # Fields to be duplicated
    author {
      id
    }
    categories {
      id
    }
    rawContent
    excerpt
    featuredImage {
      id
    }
    tags {
      id
    }
    title
 
    # Already create (and export) the inputs for the mutation
    postInputs: _echo(value: {
      status: draft,
      authorBy: {
        id: $__author
      },
      categoriesBy: {
        ids: $__categories
      },
      contentAs: {
        html: $__rawContent
      },
      excerpt: $__excerpt
      featuredImageBy: {
        id: $__featuredImage
      },
      tagsBy: {
        ids: $__tags
      },
      title: $__title
    })
      @export(as: "postInputs", type: LIST)
      @remove
  }
}
 
mutation DuplicatePosts
  @depends(on: "GetPostsAndExportData")
{
  createPosts(inputs: $postInputs) {
    status
    errors {
      __typename
      ...on ErrorPayload {
        message
      }
    }
    post {
      # Fields not to be duplicated
      id
      slug
      date
      status
 
      # Fields to be duplicated
      author {
        id
      }
      categories {
        id
      }
      rawContent
      excerpt
      featuredImage {
        id
      }
      tags {
        id
      }
      title
    }
  }
}