Skip to content

Commit

Permalink
Merge pull request #10 from minggas/feat/add-POST-route-to-Book
Browse files Browse the repository at this point in the history
Add POST route to book
  • Loading branch information
minggas authored Jun 16, 2019
2 parents bb6572e + ccfa6c8 commit 48b5836
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 6 deletions.
21 changes: 17 additions & 4 deletions routes/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,11 @@
var expect = require('chai').expect;
var MongoClient = require('mongodb').MongoClient;
var ObjectId = require('mongodb').ObjectId;
const MONGODB_CONNECTION_STRING = process.env.DB;
//Example connection: MongoClient.connect(MONGODB_CONNECTION_STRING, function(err, db) {});
var mongoose = require('mongoose');
var collection = 'test';
var Book = require('../models/Book').Book;

mongoose.connect(process.env.DB + collection + "?retryWrites=true", {useNewUrlParser:true});

module.exports = function (app) {

Expand All @@ -23,8 +26,18 @@ module.exports = function (app) {
})

.post(function (req, res){
var title = req.body.title;
//response will contain new book object including atleast _id and title
if(!req.body.title) {
res.status(400).send('Please enter title');
} else {
var title = req.body.title;
var newBook = new Book({title});
newBook.save().then(result => {
var {title, _id} = result;
res.status(200).json({title, _id});
}).catch(err => {
res.status(400).json(err);
})
}
})

.delete(function(req, res){
Expand Down
24 changes: 22 additions & 2 deletions tests/2_functional-tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,31 @@ suite('Functional Tests', function() {
suite('POST /api/books with title => create book object/expect book object', function() {

test('Test POST /api/books with title', function(done) {
//done();
chai.request(server)
.post('/api/books')
.send({
title: 'This is my first book!'
})
.end(function(err, res) {
assert.equal(res.status, 200);
assert.exists(res.body._id);
assert.equal(res.body.title, 'This is my first book!');
done();
});
});

test('Test POST /api/books with no title given', function(done) {
//done();
chai.request(server)
.post('/api/books')
.send({
title:''
})
.end(function(err, res) {
assert.equal(res.status, 400);
assert.isString(res.text)
assert.equal(res.text, 'Please enter title');
done();
});
});

});
Expand Down

0 comments on commit 48b5836

Please sign in to comment.