Building a graphql app from zero to hero using node JS and vue.js part 2

link to the part one the tutorial

If you’re here I’m guessing you are following up the tutorial from the previous part. We would continue building our full stack app by integrating a real data source to our app, which we would be using mongoDB as the database and mongoose for making our schema for mongoDB. MongoDB is a schema-less or NoSQL database that is why we are using mongoose to make schema to verify the data entering our database.To start with that we should create a folder in our source dir called models and add a file called post.js.

const mongoose = require('mongoose')
const postSchema = new mongoose.Schema({
title: {
type: String,
required: true,
minlength: 10
},
content: {
type: String,
required: true
},
createdAt: {
type: Date,
default: Date.now
}
})
// using the schema to make a collection in our DB
const Post = mongoose.model('Post', postSchema)
module.exports = Post

Here we required mongoose and use it to make a post schema which is used to make a collection in our database then we export the collection so it can be accessed outside this file. Lets create an index.js file in the model folder were all our collections would be, so we only require the index.js file and access all our database collections form there. Add this code snippet to the index.js file you just created.

const Post = require('./post')
let DB = {}
DB.Post = Post
module.exports = DB

Now go to your server.js file and require the index.js file and add the following code which will be used to connect to the database URL and use the collection as a connector between your database and graphql.

const express = require('express')
const cors = require('cors')
const morgan = require('morgan')
const bodyParser = require('body-parser')
const {
graphiqlExpress,
graphqlExpress} = require('apollo-server-express')
const mongoose = require('mongoose')
const port = 10101
const app = express()
// app modules
const schema = require('./graphql')
const DB = require('./models')
// setting up middleware for the app
app.use(cors())
app.use(morgan('dev'))
// setting up graphql
app.use('/graphql', bodyParser.json(), graphqlExpress({
schema,
context: {
DB
}
}))
// setting up a graphiql a ui for testing our query
app.use('/graphiql', graphiqlExpress({
endpointURL: '/graphql'
}))
// connecting to a mongodb database with name of db fullstack
mongoose.connect('mongodb://localhost:27107/fullstack', () => {
console.log('connected to database successfully')
})
// starting the server
app.listen(port, () => {
console.log(`starting grapql serevr on localhost:${port}`)
})

We have updated the server.js file by connecting to a real database with mongoose, then require the database which we used for adding context to our graphql in other to be able to access the data from the context parameter in our Resolver. To be able to query the data with graphiql, we need to define the datatypes and query of the model in your typeDefs.js file.

module.exports = `
type Post {
id: ID!
title: String!
content: String!
createdAt: String!
}
type Query {
allPost: [Post]!
postById(id: ID!): Post!
}
type Mutation {
createPost(title: String!, content: String!): Post
}
`

We updated our typeDef schema and added a mutation called createPost, which is used to change the state of your data. The createPost mutation would be used to create a new post. Before we are able to update or query the data in our database, lets update the resolvers.js file to match our current schema in the typeDef.js.

module.exports = {
Query: {
async allPost (root, args, {DB}) {
const posts = await DB.Post.find()
return posts
},
async postById (root, args, {DB}) {
const {id} = args
const post = await DB.Post.findById({_id: id})
if (!post) {
throw new Error('post not found ')
}
return post
}
},
Mutation: {
createPost (root, args, {DB}) {
const post = args
const newPost = new DB.Post(post)
return newPost.save()
}
}
}

I believe all is set well, now that we have connected to our database and set our query and mutation, so let start testing the API using graphiql at localhost:10101/graphiql

creating a post

It worked, we just created a post with our mutation. Lets query for all the post.

querying for all post
querying for a single post

All our tests are working fine. In our next chapter of the tutorial we will look into connecting to our client using vue.js.

I hope you gained something from this part. Remember to clap and recommend for a friend. Thanks a lot.