在graphql中嵌套片段
Posted
技术标签:
【中文标题】在graphql中嵌套片段【英文标题】:Nesting fragments in graphql 【发布时间】:2018-03-13 20:41:51 【问题描述】:我正在尝试在我的 graphql 查询中嵌套片段(无递归或无限扩展)。但是,graphql 架构不认为我的查询是有效的,或者片段定义似乎是多余的。我想要的 graphql 响应结构是:
`
"data":
"availability":
"mon":
"open":"5.00 a.m.",
"close":"10.00 p.m.",
"allday":false,
"closed":false
,
"tue":
"open":"5.00 a.m.",
"close":"10.00 p.m.",
"allday":false,
"closed":false
,
"wed":
"open":"5.00 a.m.",
"close":"10.00 p.m.",
"allday":false,
"closed":false
,
"thu":
"open":"5.00 a.m.",
"close":"10.00 p.m.",
"allday":false,
"closed":false
,
"fri":
"open":"5.00 a.m.",
"close":"10.00 p.m.",
"allday":false,
"closed":false
,
"sat":
"open":"5.00 a.m.",
"close":"10.00 p.m.",
"allday":false,
"closed":false
,
"sun":
"open":"5.00 a.m.",
"close":"10.00 p.m.",
"allday":false,
"closed":false
`
可用性的类型为 Availability 和 mon、tue 等的类型为 Day
方法 1:这不是 graphql 中的有效语法。 graphql 抛出错误(不允许以这种方式嵌套)
`
fragment Hours on Day
open
close
allday
closed
fragment DailyAvailability on Availability
mon
tue
wed
thu
fri
sat
sun
query
availability
... DailyAvailability
... Hours
`
方法 2:这可行,但似乎是多余的,因为我必须在每一天分别分配 Hours。
`
fragment Hours on Day
open
close
allday
closed
fragment DailyAvailability on Availability
mon ... Hours
tue ... Hours
wed ... Hours
thu ... Hours
fri ... Hours
sat ... Hours
sun ... Hours
query
availability
... DailyAvailability
`
请建议是否有一种方法可以嵌套片段,就像我在第一种方法中打算做的那样。
【问题讨论】:
【参考方案1】:您似乎想使用带有“别名”的字段请求。您的架构将类似于:
type QueryRoot
availability: Availability
type Availability
openingHours(forDay: WeekDay): Day
enum WeekDay
mon
tue
wed
thu
fri
sat
sun
type Day
open: String
close: String
allday: Boolean
closed: Boolean
那么这个查询会给你你所要求的:
query q
availability
mon: openingHours(forDay: mon) ... DailyAvailability
tue: openingHours(forDay: tue) ... DailyAvailability
wed: openingHours(forDay: wed) ... DailyAvailability
thu: openingHours(forDay: thu) ... DailyAvailability
fri: openingHours(forDay: fri) ... DailyAvailability
sat: openingHours(forDay: sat) ... DailyAvailability
sun: openingHours(forDay: sun) ... DailyAvailability
fragment DailyAvailability on Day
open
close
allday
closed
【讨论】:
以上是关于在graphql中嵌套片段的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Android 中发送带有片段的 graphql 查询