Skip to content

Instantly share code, notes, and snippets.

@du5rte
Created August 31, 2017 12:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save du5rte/36a117921eae9cfcbf1599f0fdcd7d4e to your computer and use it in GitHub Desktop.
Save du5rte/36a117921eae9cfcbf1599f0fdcd7d4e to your computer and use it in GitHub Desktop.
GraphlQL UnionType and InterfaceType
import {
GraphQLID,
GraphQLInt,
GraphQLString,
GraphQLObjectType,
GraphQLList,
GraphQLNonNull,
OrderTypeEnum,
GraphQLUnionType,
GraphQLInterfaceType,
GraphQLSchema
} from "graphql";
// References
// http://graphql.org/graphql-js/type/#graphqlinterfacetype
// http://graphql.org/graphql-js/type/#graphqluniontype
// https://medium.com/the-graphqlhub/graphql-tour-interfaces-and-unions-7dd5be35de0d
// export const PetType = new GraphQLUnionType({
// name: 'Pet',
// // types: [ DogType, CatType ],
// resolveType(data) {
// switch (data.type) {
// case "dog":
// return DogType;
// case "cat":
// return CatType;
// default:
// throw "Not a valid Pet type";
// }
// },
// });
export const PetType = new GraphQLInterfaceType({
name: 'Pet',
fields: {
type: { type: new GraphQLNonNull(GraphQLString) },
},
resolveType(data) {
switch (data.type) {
case "dog":
return DogType;
case "cat":
return CatType;
default:
throw "Not a valid Pet type";
}
},
});
export const DogType = new GraphQLObjectType({
name: "Dog",
interfaces: [PetType],
fields: {
type: { type: new GraphQLNonNull(GraphQLString) },
// name: { type: new GraphQLNonNull(GraphQLString) },
race: { type: new GraphQLNonNull(GraphQLString) },
// age: { type: new GraphQLNonNull(GraphQLInt) },
}
});
export const CatType = new GraphQLObjectType({
name: "Cat",
interfaces: [PetType],
fields: {
type: { type: new GraphQLNonNull(GraphQLString) },
name: { type: new GraphQLNonNull(GraphQLString) },
// race: { type: new GraphQLNonNull(GraphQLString) },
// age: { type: new GraphQLNonNull(GraphQLInt) },
}
});
export const pets = {
type: new GraphQLList(PetType),
resolve() {
const pets = [
// Cats
{type: "cat", name: "Ashes", race: "Siamsese", age: 35},
{type: "cat", name: "Tiger", race: "Bengal", age: 12},
{type: "cat", name: "Oscar", race: "Pshynx", age: 27},
// Dogs
{type: "dog", name: "Max ", race: "Greyhound", age: 6},
{type: "dog", name: "Charlie ", race: "Sheherd", age: 57},
{type: "dog", name: "Buddy", race: "Bulldog", age: 19},
];
// const randomPet = pets[Math.floor(Math.random() * pets.length)]
return pets;
}
};
export default new GraphQLSchema({
types: [
DogType,
CatType
],
query: new GraphQLObjectType({
name: "Queries",
fields: {
pets,
}
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment