AWS AppSync GraphQL-使用联合作为突变返回会导致错误

时间:2019-06-17 12:28:18

标签: graphql aws-appsync

我正在使用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的类型可以为SteppedTariffSeasonalTimeTariff,取决于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

测试“关税”值的不同模式:

  1. 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}"
      ]
    }
  }
}
  1. 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"
        }
      ]
    }
  }
}

1 个答案:

答案 0 :(得分:1)

您绝对可以在返回类型上使用并集进行突变。确保在值中包含字段__typename。您的解析器模板应返回如下内容:

{
  "id": 1,
  "type": "?",
  "values": [
    {
      "__typename": "StepTariff",
      "endDate": "2019-01-01"
    },
    {
      "__typename": "SeasonalTimeTariff",
      "endDate": "2019-01-01",
      "peakConsumption": 1.0
    }
  ]
}