如何避免GraphQL模式中的递归类型

时间:2019-01-14 10:04:25

标签: javascript graphql graphql-js apollo-server express-graphql

我有一个架构,其中一个字段引用它自己。我们如何避免这种情况。

我有一个如下所示的架构,其中“大陆”字段指的是它自己的架构。

type CountryCodeDto {
 id                                : Int
 threeLetterCode                   : String
 countryName                       : String
 capital                           : String
 telCountryCode                    : String
 officialLanguage                  : String
 currency                          : [CurrencyDto]
 regionsDto                        : [RegionsDto]
 mainLand                          : CountryCodeDto 
 twoLetterCode                     : String
}

我的问题是,我可以查询此架构的深度有多深,就像下面的查询一样。以及如何避免这种嵌套。

query {
fetchCoutries {
 id
 capital
 mainLand {
   id
   capital
   mainLand {
     id
     capital
     ..
   }
 }
}
}

1 个答案:

答案 0 :(得分:0)

如果您不需要查询大陆的大陆,则可以将其分为两种类型。这会限制深度,但会造成一些重复,例如:

type CountryCodeDto {
 id                                : Int
 threeLetterCode                   : String
 countryName                       : String
 capital                           : String
 telCountryCode                    : String
 officialLanguage                  : String
 currency                          : [CurrencyDto]
 regionsDto                        : [RegionsDto]
 mainLand                          : Mainland 
 twoLetterCode                     : String
}

type Mainland {
 id                                : Int
 threeLetterCode                   : String
 countryName                       : String
 capital                           : String
 telCountryCode                    : String
 officialLanguage                  : String
 currency                          : [CurrencyDto]
 regionsDto                        : [RegionsDto]
 twoLetterCode                     : String
}

您还可以标准化返回的数据,其中mainLand字段返回关联国家/地区的ID,而不是完整对象。如果客户需要实际显示有关大陆的信息(并可能显示其他查询),这意味着要为客户进行更多工作,但这在某些情况下可能是合适的解决方案。

 mainLand: Int

或者,您可以保留架构。从安全角度来看,无论如何都要实现类似graphql-depth-limit的解决方案是一个好主意,它可以帮助减少过多的递归查询。您还可以使用dataloader来最大程度地减少在同一请求中从数据库中重复获取同一项目的影响。

相关问题