We have our server running on localhost:3000. We will now apply GraphQL into it by following this tutorial: How to set up a powerful API with GraphQL, Koa, and MongoDB. I'll post how files should be coded for our current project.
GraphQL ↔ NodeJS + KoaJS
// server.js
const Koa = require('koa');
const mongoose = require('mongoose');
const mount = require('koa-mount');
const graphqlHTTP = require('koa-graphql');
const schema = require('./graphql/schema');
const app = new Koa();
mongoose.connect('mongodb://127.0.0.1:27017/test', {useNewUrlParser: true});
app.use(mount('/graphql', graphqlHTTP({
schema: schema,
graphiql: true
})))
module.exports = app.listen(3000, () =>
console.log('Running on http://localhost:3000/'),
);
// graphql/productType.js
const graphql = require('graphql');
const {GraphQLObjectType, GraphQLString} = graphql;
const ProductType = new GraphQLObjectType({
name: 'Product',
fields: () => ({
id: {type: GraphQLString},
title: {type: GraphQLString},
}),
});
module.exports = ProductType;
// graphql/schema.js
const {buildSchema} = require('graphql');
const {GraphQLSchema, GraphQLObjectType, GraphQLString} = require('graphql');
const productGraphQLType = require('./productType');
const Product = require('../models/Product');
const schema = buildSchema(`
type Query {
hello: String
}
`);
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
product: {
type: productGraphQLType,
args: {id: {type: GraphQLString}},
resolve(parent, args) {
return Product.findById(args.id);
},
},
},
});
module.exports = new GraphQLSchema({
query: RootQuery,
});
// database.js
const mongoose = require('mongoose');
const initDB = () => {
mongoose.connect('mongodb://127.0.0.1:27017/test', {useNewUrlParser: true});
mongoose.connection.once('open', () => {
console.log('connected to database');
});
};
module.exports = initDB;
// models/Product.js
var mongoose = require('mongoose');
const ProductSchema = new mongoose.Schema({
title: String,
});
module.exports = mongoose.model('Product', ProductSchema);
Then by running server.js
and acessing localhost:3000/graphql we can query
{
product(id: "5d67d3b89cba659baebb9765") {
title
}
}
and get
{
"data": {
"product": {
"title": "Stampler"
}
}
}