简体   繁体   中英

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. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM