简体   繁体   中英

GraphQL Schema for Nested JSON?

I am trying to use GraphQL to deal with some JSON data. I can retrieve fields from the top level no problem. I can associate separate JSON objects also no problem. My problems are occurring trying to get at data one level down. So, I have defined a type in my schema for staff. The json looks like this:

"staff": [
 {
   "id": 123,
   "name": "fred",
   "role" : "designer",
   "address": {
     "street": "main street",
     "town": "Springfield"
   }
 },
 ...
]

and the corresponding type in the schema looks like this so far:

const StaffType = new GraphQLObjectType({
    name: 'Staff',
    fields: {
      id: {type: GraphQLInt},
      name: {type: GraphQLString},
      role: {type: GraphQLString}
    }
})

This works fine as far as retrieving the id, name and role goes. My question is how can I extend StaffType to also retrieve street and town from the address field in the original JSON?

Thanks

Ok, I figured it out. I was getting hung up on the idea of a distinct Type in the schema having to refer to a separate piece of JSON whereas, in fact, I can define an AddressType in the schema to refer to the nested data and then include it in the StaffType without having to write a resolve function.

[edit to add example]

const StaffType = new GraphQLObjectType({
    name: 'Staff',
    fields: {
      id: {type: GraphQLInt},
      name: {type: GraphQLString},
      role: {type: GraphQLString},
      address: {type: AddressType}
    }
})

const AddressType = new GraphQLObjectType({
    name: 'Address',
    fields: {
      street: {type: GraphQLString},
      town: {type: GraphQLString}
    }
})

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