Skip to content

Instantly share code, notes, and snippets.

@khayyamsaleem
Created December 24, 2018 03:45
Show Gist options
  • Save khayyamsaleem/4c552f573f1992a60752fa4db82215a4 to your computer and use it in GitHub Desktop.
Save khayyamsaleem/4c552f573f1992a60752fa4db82215a4 to your computer and use it in GitHub Desktop.
const {
GraphQLObjectType,
GraphQLString,
GraphQLSchema,
GraphQLID,
GraphQLInt,
GraphQLList,
GraphQLNonNull
} = require('graphql')
const { Book, Author } = require('../models')
const AuthorType = new GraphQLObjectType({
name: 'Author',
fields: () => ({
id: { type: GraphQLID },
name: { type: GraphQLString },
age: { type: GraphQLInt },
books: {
type: new GraphQLList(BookType),
resolve(parent, args){
return Book.find({authorId: parent.id})
}
}
})
})
const BookType = new GraphQLObjectType({
name: 'Book',
fields: () => ({
id: { type: GraphQLID },
name: { type: GraphQLString },
genre: { type: GraphQLString },
author: {
type: AuthorType,
resolve(parent, args){
return Author.findById(parent.authorId)
}
}
})
})
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
book: {
type: BookType,
args: { id: { type: GraphQLID } },
resolve(parent, args){
return Book.findById(args.id)
}
},
author: {
type: AuthorType,
args: { id: { type: GraphQLID } },
resolve(parent, args){
return Author.findById(args.id)
}
},
books: {
type: new GraphQLList(BookType),
resolve(){
return Book.find({})
}
},
authors: {
type: new GraphQLList(AuthorType),
resolve(){
return Author.find({})
}
}
}
})
const Mutation = new GraphQLObjectType({
name: 'Mutation',
fields: {
addAuthor: {
type: AuthorType,
args: {
name: { type: new GraphQLNonNull(GraphQLString) },
age: { type: new GraphQLNonNull(GraphQLInt) }
},
resolve(parent, args){
const { name, age } = args
const newAuthor = new Author({
name,
age
})
return newAuthor.save()
}
},
addBook: {
type: BookType,
args: {
name: { type: new GraphQLNonNull(GraphQLString) },
genre: { type: new GraphQLNonNull(GraphQLString) },
authorId: { type: new GraphQLNonNull(GraphQLID) }
},
resolve(parent, args){
const {name, genre, authorId } = args
const newBook = new Book({
name,
genre,
authorId
})
return newBook.save()
}
}
}
})
module.exports = new GraphQLSchema({
query: RootQuery,
mutation: Mutation
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment