[英]Working with GraphQL Field Type of Objects
我想我在文档中遗漏了一些东西,但我不确定如何使用新的 GraphQLObjectType 将对象作为类型处理。 我希望从此示例数据中设置天气数据查询,但我不确定如何处理嵌套对象。 我目前有:
// Creating a Type for the Weather Object
const WeatherType = new GraphQLObjectType({
name: 'Weather',
fields: () => ({
weather: { type: GraphQLObject? },
})
});
我希望获得特定的查询并设置结构以指定更多选择数据,例如:
// Creating a Type for the Weather Object
const WeatherType = new GraphQLObjectType({
name: 'Weather',
fields: () => ({
weather: {
main: { type: GraphQLString },
// And so on
},
})
});
是否有任何参考示例?
使用嵌套的自定义类型构建架构时,您只需将字段的类型设置为其他创建类型的引用:
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,
}
}
})
将现有的 JSON 响应塑造成 GraphQL 模式时要小心——很容易被结构差异烧毁。 例如,您的示例响应中的main
字段是一个对象,但weather
字段实际上是一个数组,因此我们必须在指定字段类型时将其包装在GraphQLList
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.