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}
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With