我在我的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
}
}
}
}
`
其中,可用性的类型为可用性和 星期一,星期二等类型日
方法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:这是有效的,但似乎是多余的,因为我必须分别在每一天分摊小时数。
`
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
}
}
`
请在我的第一个方法中建议是否有办法嵌套碎片。
答案 0 :(得分:0)
这看起来像你想要使用"别名"来使用字段请求。您的架构看起来像:
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
}