var routes = require('./app_server/routes/index');
var routesApi = require('./app_api/routes/index');
...
app.use('/', routes);
app.use('/api', routesApi);
router.get('/locations', ctrlLocations.locationInfo);
router.post('/locations', ctrlLocations.locationsCreate);
/api/locations/123/reviews/abc
With the routes in index.js for reviews like the following
var ctrlReviews = require('../controllers/reviews');
...
// reviews
router.post('/locations/:locationid/reviews', ctrlReviews.reviewsCreate);
router.get('/locations/:locationid/reviews/:reviewid', ctrlReviews.reviewsReadOne);
router.put('/locations/:locationid/reviews/:reviewid', ctrlReviews.reviewsUpdateOne);
router.delete('/locations/:locationid/reviews/:reviewid', ctrlReviews.reviewsDeleteOne);
module.exports.locationsCreate = function (req, res) {
res.status(200);
res.json({"status" : "success"});
};
var sendJSONresponse = function(res, status, content) {
res.status(status);
res.json(content);
};
module.exports.locationsCreate = function (req, res) {
sendJSONresponse(res, 200, {"status" : "success"});
};
var mongoose = require('mongoose');
var Loc = mongoose.model('Location');
var sendJSONresponse = function(res, status, content) {
res.status(status);
res.json(content);
};
module.exports.locationsCreate = function (req, res) {
sendJSONresponse(res, 200, {"status" : "success"});
};
require('./app_api/models/db');
var mongoose = require('mongoose');
var Loc = mongoose.model('Location');
var sendJSONresponse = function(res, status, content) {
res.status(status);
res.json(content);
};
module.exports.locationsReadOne = function(req, res) {
Loc
.findById(req.params.locationid)
.exec(function(err, location) {
sendJSONresponse(res, 200, location);
});
};
Note further that the exec method requires a callback function which is supplied in-line. The use of the callback function allows Mongoose to get the data asynchronously, without blocking the API and your web server, and return the response when the data is returned by the database engine.
/* GET a location by the id */
module.exports.locationsReadOne = function(req, res) {
console.log('Finding location details', req.params);
if (req.params && req.params.locationid) {
Loc
.findById(req.params.locationid)
.exec(function(err, location) {
if (!location) {
sendJSONresponse(res, 404, {
"message": "locationid not found"
});
return;
} else if (err) {
console.log(err);
sendJSONresponse(res, 404, err);
return;
}
console.log(location);
sendJSONresponse(res, 200, location);
});
} else {
console.log('No locationid specified');
sendJSONresponse(res, 404, {
"message": "No locationid in request"
});
}
};
Note: Recognize the use of HTTP response codes (404, 200) above.
/* GET a list of all locations */
module.exports.locationsList = function(req, res) {
console.log('Getting locations list');
Loc
.find()
.exec(function(err, results) {
if (!results) {
sendJSONresponse(res, 404, {
"message": "no locations found"
});
return;
} else if (err) {
console.log(err);
sendJSONresponse(res, 404, err);
return;
}
console.log(results);
sendJSONresponse(res, 200, buildLocationList(req, res, results));
});
};
var buildLocationList = function(req, res, results) {
var locations = [];
results.forEach(function(obj) {
locations.push({
name: obj.name,
address: obj.address,
rating: obj.rating,
_id: obj._id
});
});
return locations;
};
/* POST a new location */
/* /api/locations */
module.exports.locationsCreate = function(req, res) {
console.log(req.body);
Loc
.create({
name: req.body.name,
address: req.body.address,
facilities: req.body.facilities.split(","),
coords: [parseFloat(req.body.lng), parseFloat(req.body.lat)],
openingTimes: [{
days: req.body.days1,
opening: req.body.opening1,
closing: req.body.closing1,
closed: req.body.closed1,
}, {
days: req.body.days2,
op ening: req.body.opening2,
closing: req.body.closing2,
closed: req.body.closed2,
}]
}, function(err, location) {
if (err) {
console.log(err);
sendJSONresponse(res, 400, err);
} else {
console.log(location);
sendJSONresponse(res, 201, location);
}
}
);
};
/* Update one Book entry */
module.exports.bookUpdateOne = function(req, res) {
console.log("Updating a book entry with id of " + req.params.id);
console.log(req.body);
bookModel
.findOneAndUpdate(
{ _id: req.params.id },
{ $set: {"bookTitle": req.body.bookTitle, "bookAuthor": req.body.bookAuthor}},
function(err, response) {
if (err) {
sendJSONresponse(res, 400, err);
} else {
sendJSONresponse(res, 201, response);
}
}
);
};
/* Delete one Book */
module.exports.bookDeleteOne = function(req, res) {
console.log("Deleting book entry with id of " + req.params.id);
console.log(req.body);
bookModel
.findByIdAndRemove(req.params.id)
.exec (
function(err, response) {
if (err) {
sendJSONresponse(res, 404, err);
} else {
sendJSONresponse(res, 204, null);
}
}
);
};
$ npm install --save request
var request = require('request');
var apiOptions = {
server : "http://localhost:3000" // Change as needed
};
var requestOptions = {
url : "http://yourapi.com/api/path", method : "GET",
json : {},
qs: {}
};
request( requestOptions,
function(err, response, body) {
if (err) {
console.log(err);
} else if (response.statusCode === 200) {
console.log(body);
} else {
console.log(response.statusCode);
}
}
);
/* GET books lists */
module.exports.list = function(req, res){
var requestOptions, path;
path = '/api/books';
requestOptions = {
url : apiOptions.server + path,
method : "GET",
json : {},
qs : {}
};
request(
requestOptions,
function(err, response, body) {
renderListPage(req, res, body);
}
);
};
/* Render the book list page */
var renderListPage = function(req, res, responseBody){
res.render('book-list', {
title: 'Book List',
pageHeader: {
title: 'Book List'
},
books: responseBody
});
};
/* Book Show */
module.exports.edit = function(req, res) {
var requestOptions, path;
path = "/api/books/" + req.params.id;
requestOptions = {
url : apiOptions.server + path,
method : "GET",
json : {}
};
request(
requestOptions,
function(err, response, body) {
renderShowPage(req, res, body);
}
);
};
/* Render the book show page */
var renderShowPage = function(req, res, responseBody){
res.render('book-show', {
title: 'Book Info',
pageHeader: {
title: 'Book Info'
},
book: responseBody
});
};
/* Book Add */
module.exports.add = function(req, res) {
res.render('book-add', { title: 'Add Book' });
};
/* Book Add Post */
module.exports.addPost = function(req, res){
var requestOptions, path, postdata;
path = '/api/books/';
postdata = {
bookTitle: req.body.bookTitle,
bookAuthor: req.body.bookAuthor
};
requestOptions = {
url : apiOptions.server + path,
method : "POST",
json : postdata
};
request(
requestOptions,
function(err, response, body) {
if (response.statusCode === 201) {
res.redirect('/book-list');
} else {
_showError(req, res, response.statusCode);
}
}
);
};
/* Book Edit */
module.exports.edit = function(req, res) {
var requestOptions, path;
path = "/api/books/" + req.params.id;
requestOptions = {
url : apiOptions.server + path,
method : "GET",
json : {}
};
request(
requestOptions,
function(err, response, body) {
renderEditPage(req, res, body);
}
);
};
/* Render the book edit page */
var renderEditPage = function(req, res, responseBody){
res.render('book-edit', {
title: 'Book Edit',
pageHeader: {
title: 'Book Edit'
},
book: responseBody
});
};
/* Book Edit Post */
module.exports.editPost = function(req, res){
var requestOptions, path, postdata;
var id = req.params.id;
path = '/api/books/' + id;
postdata = {
bookTitle: req.body.bookTitle,
bookAuthor: req.body.bookAuthor
};
requestOptions = {
url : apiOptions.server + path,
method : "PUT",
json : postdata
};
request(
requestOptions,
function(err, response, body) {
if (response.statusCode === 201) {
res.redirect('/book-list');
} else {
_showError(req, res, response.statusCode);
}
}
);
};
/* Book Delete */
module.exports.del = function(req, res) {
var requestOptions, path;
path = "/api/books/" + req.params.id;
requestOptions = {
url : apiOptions.server + path,
method : "GET",
json : {}
};
request(
requestOptions,
function(err, response, body) {
renderDeletePage(req, res, body);
}
);
};
/* Render the blook delete page */
var renderDeletePage = function(req, res, responseBody){
res.render('book-delete', {
title: 'Book Delete',
pageHeader: {
title: 'Book Delete'
},
blog: responseBody
});
};
/* Book Delete Post */
module.exports.deletePost = function(req, res){
var requestOptions, path, postdata;
var id = req.params.id;
path = '/api/book/' + id;
requestOptions = {
url : apiOptions.server + path,
method : "DELETE",
json : {}
};
request(
requestOptions,
function(err, response, body) {
if (response.statusCode === 204) {
res.redirect('/book-list');
} else {
_showError(req, res, response.statusCode);
}
}
);
};