I am building a JSON restful web api in Node.js and so far I only got the main structure, however I am not 100% sure I am doing this correct from scratch, I still have to get used to the fact that Node.js is event driven.
Directory structure:
1. main.js
2. modules
a. router.js
b. config.js
c. routes.js
1. main.js - contains the main entry point - node main.js
2. modules - folder that contains all the modules.
2a. router.js - contains "singleton" class module that will handle routing.
var Router = function(routes){
this.routes = routes;
Router.route = function(){
console.log('routing from singleton router...');
};
return Router;
};
module.exports = Router;
2b. config.js - contains the global configuration.
exports.config = {
port: 9090
};
2c. routes.js - contains the global routing schema, the router module will get the module injected (from main.js)
exports.routes = {
'POST /users': { 'controller': 'users', 'action': 'create' },
'GET /users': { 'controller': 'users', 'action': 'getSelf' },
'GET /users/:uid/posts/:pid': { 'controller': 'users', 'action': 'getPostsFromUser' }
};
This is the structure so far, I am planning to extend it to this directory structure:
1. main.js
2. modules
a. router.js
b. config.js
c. routes.js
d. loader.js (model loader, connection pool etc.)
e. validator.js (validates input)
d. controller.js (main controller, how to inherit from this? through inheritance?)
3. controllers - contains controllers
4. models - contains models
How to handle connection pooling in the structure? Would it be an idea to create a "registry" class, I come from a PHP background and that is how I would share objects, instead of dependency injection.
sample registry.js
var Registry = function(){
this.data = {};
Registry.push = function(key, value){
return this.data[key] = value;
};
Registry.pull = function(key){
return this.data[key];
}
return Registry;
};
module.exports = Registry;
As I said, I am kinda new to Node.js and I want to make sure I get it right from scratch.
If you got any suggestions, comments, tips I really appreciate your help and time.