Book Image

Node.js By Example

Book Image

Node.js By Example

Overview of this book

If you are a JavaScript developer with no experience with Node.js or server-side web development, this book is for you. It will lead you through creating a fairly complex social network. You will learn how to work with a database and create real-time communication channels.
Table of Contents (13 chapters)
12
Index

Refactoring the API


If you check the files that you ended up with in the previous chapter, you will see that the backend/API.js file is quite big. It will get more and more difficult to work with. We are going to refactor this part of our system.

We have a bunch of helper methods that are used all over the route handlers. Functions such as response, error, and getDatabaseConnection may be placed in an external module. We will create a new api folder under the backend directory. The newly created helpers.js file will host all these utility functions:

// backend/api/helpers.js
var MongoClient = require('mongodb').MongoClient;
var querystring = require('querystring');
var database;

var response = function(result, res) { ... };
var error = function(message, res) { ... };
var getDatabaseConnection = function(callback) { ... };
var processPOSTRequest = function(req, callback) { ... };
var validEmail = function(value) { ... };
var getCurrentUser = function(callback, req, res) { ... };

module.exports...