Interagire con l'API GraphQLModificare il percorso in cui un campo viene stampato nella risposta
Modificare il percorso in cui un campo viene stampato nella risposta
Questa domanda è apparsa su Reddit:
I have:
allMdx { edges { node { frontmatter { date(formatString: "MMMM DD, YYYY") } } } }I need
frontmatter.dateto bepublishedAt:allMdx { edges { node { publishedAt: frontmatter{date(formatString: "MMMM DD, YYYY")} } } }Problem is, when I do this, I end up with:
{ "publishedAt": { "date": "February 06, 2021" } }Instead of (which is what I need):
{ "publishedAt": "February 06, 2021" }Is it even possible to alias nested fields like this?
In altre parole, è possibile chiedere al server GraphQL di appiattire la forma della risposta? E, in tal caso, come si fa?
Ecco una soluzione con Gato GraphQL, che utilizza le seguenti estensioni:
- Multiple Query Execution, per
@exportil valore di una variabile tra le operazioni GraphQL - PHP Functions via Schema, per stampare di nuovo questo valore nella posizione desiderata tramite il campo
_echo
Con @export, possiamo fare in modo che una prima operazione di query esporti un risultato in una variabile, e poi dichiarare una seconda operazione di query che leggerà questa variabile e la stamperà nella posizione attesa nella risposta:
query ExportDate
{
allMdx {
edges {
node {
frontmatter {
date(formatString: "MMMM DD, YYYY")
@export(as: "date")
}
}
}
}
}
query PrintRelocatedDate($date: String)
@depends(on: "ExportDate")
{
allMdx {
edges {
node {
publishedAt: _echo(value: $date)
}
}
}
}...e poi eseguendo la query (passando ?operationName=PrintRelocatedDate) si otterrà questa risposta:
{
"data": {
"allMdx": {
"edges": [
{
"frontmatter": {
"publishedAt": "February 06, 2021"
},
"publishedAt": "February 06, 2021"
}
]
}
}
}