What is the correct way to nest data within a graphql?

Viewed 88

I have an address in my database that I've put into a location hash. The hash contains separate keys for streetAddress, city, state, and zipCode. I've nested the data like so in my graphql schema file:

location: {
    streetAddress: { 
      type: String,
      required: true,
      unqiue: true
    },
    city: {
      type: String,
      required: true
    }, 
    state: {
      type: String,
      required: true
    },
    zipCode: {
      type: Number,
      required: true
    }
  }

And I've implemented the schema type like this:

fields: () => ({
    id: { type: GraphQLID },
    name: { type: GraphQLString },
    id: {type: GraphQLID},
    phoneNum: { type: GraphQLString },
    location: {
      streetAddress: { type: GraphQLString },
      city: { type: GraphQLString },
      state: { type: GraphQLString },
      zipCode: { type: GraphQLInt }
    }
    ...

However, I get an error message saying that the output type is undefined when I try to do a query in graphql:

"message": "The type of RestaurantType.location must be Output Type but got: undefined."

I believe I understand where the error is coming from; I'm assuming that it expects location to have a type as well. What would be the correct syntax for doing this/fixing this error message?

1 Answers

As you guessed, you cannot have nested fields like that. You need to create a separate type for every object in your schema. First create the type:

const Location = new GraphQLObjectType({
  name: 'Location',
  fields: () => ({
    streetAddress: { type: GraphQLString },
    city: { type: GraphQLString },
    state: { type: GraphQLString },
    zipCode: { type: GraphQLInt }
  }),
})

Then use it:

const Restaurant = new GraphQLObjectType({
  name: 'Restaurant',
  fields: () => ({
    id: { type: GraphQLID },
    name: { type: GraphQLString },
    location: { type: Location },
  }),
})

or if you don't need to reuse the type, you can define it inline like this:

const Restaurant = new GraphQLObjectType({
  name: 'Restaurant',
  fields: () => ({
    id: { type: GraphQLID },
    name: { type: GraphQLString },
    location: {
      type: new GraphQLObjectType({
        name: 'Location',
        fields: () => ({
          streetAddress: { type: GraphQLString },
          city: { type: GraphQLString },
          state: { type: GraphQLString },
          zipCode: { type: GraphQLInt }
        }),
      })
    },
  }),
})
Related