我正在使用AWS AppSync创建GraphQL模式,我想使用Union
作为突变返回。我想这样写突变:
mutation addUpdateTariff($tariff: TariffInput!, $seasonalTimeTariff: [SeasonalTimeTariffInput!]) {
addUpdateTariff(tariff: $tariff, seasonalTimeTariff: $seasonalTimeTariff) {
id
type
values {
... on SteppedTariff {
endDate
}
... on SeasonalTimeTariff {
endDate
peakConsumption
}
}
}
}
但是我遇到了这个错误:
Request failed with status code 400
字段values
的类型可以为SteppedTariff
或SeasonalTimeTariff
,取决于addUpdateTariff
突变的输入。据我搜索,Union
仅用于查询,并且没有找到文档说明不能以其他方式使用。
我丢失了某些东西还是真的无法使用Union
?
架构:
type Tariff {
id: ID!
type: TariffType!
values: [TariffValue!]
}
type SteppedTariff {
endDate: AWSDate
}
type SeasonalTimeTariff {
endDate: AWSDate
peakConsumption: Float
}
union TariffValue = SeasonalTimeTariff | SteppedTariff
测试“关税”值的不同模式:
values: [String]
查询:
mutation addUpdateTariff($tariff: TariffInput!, $seasonalTimeTariff: [SeasonalTimeTariffInput!]) {
addUpdateTariff(tariff: $tariff, seasonalTimeTariff: $seasonalTimeTariff) {
id
type
values
}
}
回复:
{
"data": {
"addUpdateTariff": {
"id": "843eadcf-48bd-4d58-93ec-8bbe96db3635",
"type": "SeasonalTime",
"values": [
"{endDate=2019-02-02}"
]
}
}
}
values: [SeasonalTimeTariff]
查询:
mutation addUpdateTariff($tariff: TariffInput!, $seasonalTimeTariff: [SeasonalTimeTariffInput!]) {
addUpdateTariff(tariff: $tariff, seasonalTimeTariff: $seasonalTimeTariff) {
id
type
values {
endDate
}
}
}
回复:
{
"data": {
"addUpdateTariff": {
"id": "7f77c5d9-2b06-4bb8-a678-10996addc4e1",
"type": "SeasonalTime",
"values": [
{
"endDate": "2019-02-02"
}
]
}
}
}
答案 0 :(得分:1)
您绝对可以在返回类型上使用并集进行突变。确保在值中包含字段__typename
。您的解析器模板应返回如下内容:
{
"id": 1,
"type": "?",
"values": [
{
"__typename": "StepTariff",
"endDate": "2019-01-01"
},
{
"__typename": "SeasonalTimeTariff",
"endDate": "2019-01-01",
"peakConsumption": 1.0
}
]
}