Lezione 4: Duplicare più articoli del blog alla volta
Possiamo estendere la lezione precedente del tutorial per duplicare più articoli con una singola richiesta GraphQL.
Query GraphQL per duplicare più articoli alla volta
Affinché questa query GraphQL funzioni, la Configurazione dello schema applicata all'endpoint deve avere le Mutazioni annidate abilitate
Questa query GraphQL duplica gli articoli recuperati tramite le variabili $limit e $offset fornite:
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
}
}
}Passo dopo passo: creazione della query GraphQL
Di seguito è riportata l'analisi dettagliata del funzionamento della query.
Estensione della lezione "Duplicare un articolo del blog"
La lezione precedente adotta la seguente strategia (sulla query GraphQL del secondo approccio):
- Esportare gli ID delle risorse dai campi (inclusi i campi di connessione):
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")
}
}- Creare l'oggetto input per
createPost(input:)a partire da quelle variabili dinamiche:
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
}) {
# ...
}
}Grazie all'estensione Field to Input, possiamo creare l'oggetto input già nella prima operazione ed esportare tutti i dati necessari dell'articolo sotto un'unica variabile dinamica:
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")
}
}Poi, nella mutazione seguente, createPost(input:) riceve direttamente la variabile dinamica $postInputs:
mutation DuplicatePost
@depends(on: "GetPostAndExportData")
{
createPost(input: $postInputs) {
# ...
}
}Recuperare più articoli
Dobbiamo convertire la query per recuperare i più articoli da duplicare:
- Interrogare gli articoli tramite
posts(pagination: { limit : $limit, offset: $offset}) { ... } - Esportare
postInputscome lista (ovvero un array contenente tutti gli input per gli articoli interrogati)
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
)
}
}Creare più articoli in una singola query GraphQL
La variabile dinamica $postInputs contiene ora un array con tutti i dati di input per ciascuno degli articoli da duplicare:
[
{
"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"
}
]Infine, chiamiamo la mutazione in massa createPosts per creare tutti gli articoli passando i dati degli input esportati:
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
}
}
}Infine, chiamiamo la mutazione in massa createPosts per creare tutti gli articoli passando tutti gli input:
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
}
}
}Rimuovere i dati non necessari
Il passaggio finale consiste nel rimuovere tramite @remove tutti i campi che sono ausiliari (e il cui output non è necessario stampare nella risposta).
La query GraphQL consolidata è:
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
}
}
}