[英]Working with GraphQL Field Type of Objects
I think I am missing something in the docs but I am not sure how to handle objects as the type withing a new GraphQLObjectType.我想我在文档中遗漏了一些东西,但我不确定如何使用新的 GraphQLObjectType 将对象作为类型处理。 I am looking to set up the queries for weather data from this sample data , and I am not sure how to handle the nested objects.
我希望从此示例数据中设置天气数据查询,但我不确定如何处理嵌套对象。 I currently have:
我目前有:
// Creating a Type for the Weather Object
const WeatherType = new GraphQLObjectType({
name: 'Weather',
fields: () => ({
weather: { type: GraphQLObject? },
})
});
I am looking to get specific with the queries and set up the structure to specify more select data like:我希望获得特定的查询并设置结构以指定更多选择数据,例如:
// Creating a Type for the Weather Object
const WeatherType = new GraphQLObjectType({
name: 'Weather',
fields: () => ({
weather: {
main: { type: GraphQLString },
// And so on
},
})
});
Are there any references to examples of this?是否有任何参考示例?
When constructing a schema with nested custom types, you just set the type of the field to a reference of your other created type:使用嵌套的自定义类型构建架构时,您只需将字段的类型设置为其他创建类型的引用:
const WeatherType = new GraphQLObjectType({
name: 'Weather',
fields: {
id: {
type: GraphQLInt,
}
main: {
type: GraphQLString,
}
description: {
type: GraphQLString,
}
icon: {
type: GraphQLString,
}
}
})
const MainType = new GraphQLObjectType({
name: 'Main',
fields: {
temp: {
type: GraphQLFloat,
}
pressure: {
type: GraphQLFloat,
}
humidity: {
type: GraphQLFloat,
}
tempMin: {
type: GraphQLFloat,
resolve: (obj) => obj.temp_min
}
tempMax: {
type: GraphQLFloat,
resolve: (obj) => obj.temp_max
}
}
})
const WeatherSummaryType = new GraphQLObjectType({
name: 'WeatherSummary',
fields: {
weather: {
type: new GraphQLList(WeatherType),
}
main: {
type: MainType,
}
}
})
Be careful when molding existing JSON responses into GraphQL schemas -- it's easy to get burned by differences in structure.将现有的 JSON 响应塑造成 GraphQL 模式时要小心——很容易被结构差异烧毁。 For example, the
main
field in your sample response is an object, but the weather
field is actually an array, so we have to wrap it in GraphQLList
when specifying the type for the field.例如,您的示例响应中的
main
字段是一个对象,但weather
字段实际上是一个数组,因此我们必须在指定字段类型时将其包装在GraphQLList
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.