使用对象的GraphQL字段类型

时间:2018-11-05 15:14:00

标签: javascript graphql

我认为我在文档中缺少某些内容,但是我不确定如何使用新的GraphQLObjectType将对象作为类型来处理。我正在寻找建立来自this sample data的天气数据查询的方法,但不确定如何处理嵌套对象。我目前有:

// 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
        },
    })
});

是否有对此示例的引用?

1 个答案:

答案 0 :(得分:1)

使用嵌套的自定义类型构造架构时,只需将字段的类型设置为其他已创建类型的引用:

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