DEV Community

Cover image for Fullstacking: GraphQL ↔ KoaJS
Mark Kop
Mark Kop

Posted on • Updated on

Fullstacking: GraphQL ↔ KoaJS

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/'),
);

Enter fullscreen mode Exit fullscreen mode
// 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;

Enter fullscreen mode Exit fullscreen mode
// 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,
});

Enter fullscreen mode Exit fullscreen mode
// 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;

Enter fullscreen mode Exit fullscreen mode
// models/Product.js
var mongoose = require('mongoose');

const ProductSchema = new mongoose.Schema({
  title: String,
});

module.exports = mongoose.model('Product', ProductSchema);
Enter fullscreen mode Exit fullscreen mode

Then by running server.js and acessing localhost:3000/graphql we can query

{
  product(id: "5d67d3b89cba659baebb9765") {
    title
  }
}
Enter fullscreen mode Exit fullscreen mode

and get

{
  "data": {
    "product": {
      "title": "Stampler"
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

http://localhost:3000/graphql printscreen

References:

Top comments (0)