与 GraphQL API 交互更改字段在响应中输出路径的方法
更改字段在响应中输出路径的方法
这个问题发布在 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?
换句话说,是否可以让 GraphQL 服务器将响应的结构扁平化?如果可以,该如何实现?
以下是使用 Gato GraphQL 的解决方案,利用了以下扩展:
- Multiple Query Execution:用于在 GraphQL 操作之间通过
@export导出变量的值 - PHP Functions via Schema:通过
_echo字段将该值重新输出到响应中的目标位置
使用 @export,我们可以让第一个 query 操作将某些结果导出到变量,然后声明第二个 query 操作,读取该变量并将其输出到响应中的预期位置:
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)
}
}
}
}...然后执行该 query(传入 ?operationName=PrintRelocatedDate)将产生以下响应:
{
"data": {
"allMdx": {
"edges": [
{
"frontmatter": {
"publishedAt": "February 06, 2021"
},
"publishedAt": "February 06, 2021"
}
]
}
}
}