Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add POST route to book #10

Merged
merged 4 commits into from
Jun 16, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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