Book Image

Node.js By Example

Book Image

Node.js By Example

Overview of this book

Table of Contents (18 chapters)
Node.js By Example
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
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...