diff --git a/routes/api.js b/routes/api.js index bb3e536..f8b9d56 100644 --- a/routes/api.js +++ b/routes/api.js @@ -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) { @@ -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){ diff --git a/tests/2_functional-tests.js b/tests/2_functional-tests.js index 32635e4..ea61dce 100644 --- a/tests/2_functional-tests.js +++ b/tests/2_functional-tests.js @@ -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(); + }); }); });