【问题标题】:Creating a schema with varying nested key values创建具有不同嵌套键值的模式
【发布时间】:2020-07-17 14:43:13
【问题描述】:

我什至不确定如何命名它,但我在获取非空值时遇到了问题......我希望有人能帮助我并告诉我我做错了什么。 ..

我从中提取的 api 返回以下格式...

{
    "countrytimelinedata": [
        {
            "info": {
                "ourid": 167,
                "title": "USA",
                "code": "US",
                "source": "https://thevirustracker.com/usa-coronavirus-information-us"
            }
        }
    ],
    "timelineitems": [
        {
            "1/22/20": {
                "new_daily_cases": 1,
                "new_daily_deaths": 0,
                "total_cases": 1,
                "total_recoveries": 0,
                "total_deaths": 0
            },
            "1/23/20": {
                "new_daily_cases": 0,
                "new_daily_deaths": 0,
                "total_cases": 1,
                "total_recoveries": 0,
                "total_deaths": 0
            }
         }
     ]
}

我的问题是我无法使用架构中的内容在时间线项数组中提取任何内容

我的架构如下

gql`
  extend type Query {
    getCountryData: getCountryData
  }
  type getCountryData {
    countrytimelinedata: [countrytimelinedata]
    timelineitems: [timelineitems]
  }
  type countrytimelinedata {
    info: Info
  }
  type Info {
    ourid: String!
    title: String!
    code: String!
    source: String!
  }
  type timelineitems {
    timelineitem: [timelineitem]
  }
  type timelineitem {
    new_daily_cases: Int!
    new_daily_deaths: Int!
    total_cases: Int!
    total_recoveries: Int!
    total_deaths: Int!
  }
`;

我希望这是问这个问题的正确地方,如果我不理解一些基本的东西,我很抱歉。

我应该使用更好的东西吗?

提前谢谢你

【问题讨论】:

    标签: graphql schema apollo


    【解决方案1】:

    GraphQL 不支持使用动态键返回对象,因此无法在您的架构 without using a custom scalar 中表示相同的数据结构。但是,使用自定义标量的问题是您丢失了 GraphQL 提供的数据类型验证。您最好将 API 返回的数据转换为 可以 在您的架构中表达的格式。

    type CountryData {
      timelineItems: [TimelineItemsByDate!]!
    }
    
    type TimelineItemsByDate {
      date: String!
      newDailyCases: Int!
      newDailyDeaths: Int!
      totalCases: Int!
      totalRecoveries: Int!
      totalDeaths: Int!
    }
    

    请注意,我已经转换了上面示例中的类型和字段名称以反映命名约定。此外,如果 API 出于某种原因将某些数据作为数组返回,但它只返回数组中的单个项目,我只会将其转换为对象,而不是将其作为 List 保存在您的架构中。

    【讨论】:

    • 嘿丹尼尔,这很有意义,非常感谢您的帮助!
    猜你喜欢
    • 2020-07-31
    • 2023-03-02
    • 1970-01-01
    • 1970-01-01
    • 2016-03-22
    • 1970-01-01
    • 2019-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多