Interacting with the GraphQL APIChanging the path to where a field is printed in the response
Changing the path to where a field is printed in the response
This question appeared on Reddit:
I have:
allMdx { edges { node { frontmatter { date(formatString: "MMMM DD, YYYY") } } } }
I need
frontmatter.date
to 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 other words, is it possible to tell the GraphQL server to flatten the shape of the response? And, if so, how to do it?
Here is a solution with Gato GraphQL, making use of the following extensions:
- Multiple Query Execution, to
@export
the value of a variable across GraphQL operations - PHP Functions via Schema, to print this value again on the desired location via the
_echo
field
With @export
, we can have a first query operation export some result to a variable, and then declare a second query operation that will read this variable and print it on the expected location in the response:
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)
}
}
}
}
...and then executing the query (passing ?operationName=PrintRelocatedDate
) will produce this response:
{
"data": {
"allMdx": {
"edges": [
{
"frontmatter": {
"publishedAt": "February 06, 2021"
},
"publishedAt": "February 06, 2021"
}
]
}
}
}