- express
- graphql
- express-graphql
- mongoose
- cors (optional)
npm i express graphql express-graphql mongoose cors
const express = require('express');
const graphqlHTTP = require('express-graphql');
const mongoose = require('mongoose');
const cors = require('cors');
const schema = require('./schema/schema');
const app = express();
mongoose.connect('mongodb://localhost:27017/gql-demo');
mongoose.connection.once('open', () => {
console.log('connected to database..');
});
app.use('/graphql', graphqlHTTP({
schema,
// optional UI:
graphiql: true
}));
app.listen(4000, () => {
console.log('Listen on port 4000..');
});
app.use(cors());
const graphql = require('graphql');
const Book = require('../models/book');
const Author = require('../models/author');
const {
GraphQLObjectType,
GraphQLString,
GraphQLSchema,
GraphQLID,
GraphQLInt,
GraphQLList,
GraphQLNonNull
} = graphql;
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) {
// code to get data from db / other source
//return _.find(books, { id: args.id });
return Book.findById(args.id);
}
},
books: {
type: GraphQLList(BookType),
resolve(parent, args) {
//return books;
return Book.find({});
}
}
}
});
const Mutation = new GraphQLObjectType({
name: 'Mutation',
fields: {
addBook: {
type: BookType,
args: {
name: { type: new GraphQLNonNull(GraphQLString) },
genre: { type: new GraphQLNonNull(GraphQLString) }
},
resolve(parent, args) {
let book = new Book({
name: args.name,
genre: args.genre
});
return book.save();
}
}
}
});
module.exports = new GraphQLSchema({
query: RootQuery,
mutation: Mutation
});
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const bookSchema = new Schema({
name: String,
genre: String,
authorId: String
});
module.exports = mongoose.model('Book', bookSchema);