Node.js
is a better tool to utilize verses ASP.NET in REST service scenarios. Going along this line, I really wanted to start shifting from the "hello world throw all your code in one file" and start structuring it like I would a C# project breaking out routes from the main file and abstracting out the database functionality. So without further discussion let's dive in.
MongoDB
related code also mixed in there.Express
init calls:Only thing left in my mind is to pull the hard coded port number (1338) into a config file or constants file.var express = require('express'); var app = express(); app.use(require('./routes')); app.listen(1338);
For those keeping up with this deep dive, not too much new code here outside of defining thevar express = require('express'); var mongojs = require('mongojs'); var dburl = 'localhost/day2innode'; var collections = ['posts']; var db = mongojs(dburl, collections); var postData = db.collection('posts'); var router = express.Router(); router.get('/api/Test', function (request, response) { var id = request.params.id; var newData = { 'id': id, 'likes': 2 }; postData.insert(newData, function (err, post) { if (err) { return response.json({ message: err }); } return response.json({ message: true }); }); }); module.exports = router;
module.exports
and express.Router
. One thing I want to do in this file is to utilize mongoose
to clean up the MongoDB calls and to pull the collection and database url from a configuration file similiar to the server port number in the server.js file.
MongoDB
database code I wrote the other night.
Lastly, all of the code thus far is committed on GitHub.