For those not yet clicked , here's an implementation using appolo graphql
Graphql schema:
interface Animal {
name: String
age: String
dob: String
owner: String
sound: String
}
type Dog implements Animal {
name: String
age: String
dob: String
owner: String
sound: String
color: String
}
type Cat implements Animal {
name: String
age: String
dob: String
owner: String
sound: String
weight: String
}
Here Animal is an abstract type and the Dog and Cat has similar properties excpet color and weight which is different.
Resolver:
Owner: {
animal: (creator) => {
return animals.find(anm => creator.name == anm.owner)
}
},
Animal: {
__resolveType(animal) {
if (animal.sound == "Bark") {
return 'Dog'
} else {
return 'Cat'
}
}
},
So a particular owner may have a cat or dog, so we have this scenario where if it's a dog output the color property and if it's a cat output weight. Consider it more like an if else statement.
An example query:
owner(id: $id) {
animal {
... on Cat {
weight
}
... on Dog {
color
}
}
}
Same query using fragments:
owner(id: $id) {
animal {
...Catto
...Doggo
}
}
fragment Catto on Cat {
weight
}
fragment Doggo on Dog {
color
}