Code coverage report for vatican/lib/vatican.js

Statements: 59.12% (81 / 137)      Branches: 53.66% (22 / 41)      Functions: 52.17% (12 / 23)      Lines: 60.15% (80 / 133)      Ignored: none     

All files » vatican/lib/ » vatican.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 2541                     1 1   1               1 6 6 6 6         6 6 4   4   4 4 4 4 4     1 1     1 1     1 5 5 5 5 5 4   5             1 6 1 1     5 1 1       1               1 3 3 3       3 5 5 5 5   3               1                 1 1   1   1 1   1 1 1 1 1 1       1           1 2 2 2 2 2                                                     1               1 3 3 3 3 3 3                       1                         1                                                 1                             1 5  
var http = require("http"), 
    logger = require("./logger"), 
    fs = require("fs"),
    vaticanResp = require("./vaticanResponse"),
    handlerParser = require("./handlerParser"),
    processingChain = require("./processingChain"),
    mongoose = require("mongoose"),
    _ = require("lodash"),
    path = require("path");
 
 
module.exports = Vatican;
var CONFIG_FILE_PATH = process.cwd() + "/vatican-conf.json";
 
var DEFAULT_CONFIG = {
    cors: false,
    db: {
        host: 'localhost',
        dbname: 'vatican-project'        
    }
}
 
function Vatican(options) {
    var config = null;
    this.dbconn = null
    try {
        config = (options) ? options : require(CONFIG_FILE_PATH);
    } catch(ex) {
        logger.error("Error loading config file '" + CONFIG_FILE_PATH + "': " + ex);
        return;
    }
    this.options = _.defaults( config, DEFAULT_CONFIG);
    this.checkOptions();
    this.requestParser = config.requestParser ? require(config.requestParser) : require("./defaultRequestParser");
 
    this.handlers = {};
 
    this.parseHandlers();
    this.paths = [];
    this.server = null;
    this.preprocessors = new processingChain();
    this.postprocessors = new processingChain();
}
 
Vatican.prototype.preprocess = function(fn, endpointNames) {
    this.preprocessors.add({fn: fn, names: endpointNames})
}
 
Vatican.prototype.postprocess = function(fn, endpointNames) {
    this.postprocessors.add({fn: fn, names: endpointNames});
}
 
Vatican.prototype.parseHandlers = function(cb) {
    var dir = isAbsolutePath(this.options.handlers) ? this.options.handlers : process.cwd() + "/" + this.options.handlers;
    var self = this;
    handlerParser.parse(dir, function(err, path) {
        Iif(typeof cb == 'function' && err) return cb(err)
        if(!err) {
            self.paths = path;
        }
        if(typeof cb == 'function') cb(self.paths)
    }) 
};
 
/**
 Makes sure that the required options are there
*/
Vatican.prototype.checkOptions = function() {
    if( !this.options.port ) {
        logger.error("Port not specified, throwing error!");
        throw new Error("Port not specified");
    }
 
    if( !this.options.handlers ) {
        logger.error("Handlers folder not specified, throwing error!");
        throw new Error("Handlers folder not specified");
    }
};
 
Vatican.prototype.parseRequest = function( req, template, originalReq , cb) {
    this.requestParser.parse(req, template, originalReq, cb);
};
 
/**
    Checks all paths until one that matches the current url is found.
    If there is no match, then false is returned
*/
Vatican.prototype.findMethod = function( url, method ) {
    var path = (url.indexOf("?") == -1) ? url : url.split("?")[0];
    var nmbrOfParts = path.split("/").length;
    var nmbrOfPartsPath = null,
        regExpStr = null,
        regExp = null
   
    var match = _.find(this.paths, function(item) { 
        regExpStr = item.url.replace(/\:.+(\/)?/g,".+$1");
        nmbrOfPartsPath = item.url.split("/").length;
        regExp = new RegExp(regExpStr + "$");
        return  nmbrOfPartsPath == nmbrOfParts && (item.method.toLowerCase() === method.toLowerCase()) && regExp.test(path);
    });
    return match;
};
 
/*
    Adds usefull methods and properties to node's original request object.
    Note: Right now, there is nothing to be added, but I left the method here in case
    I think of something in the future.
*/
Vatican.prototype.createRequest = function(req) {
    return req;
};
 
/*
    Reads the handler code, comments out the annotation, then 
    loads the code as a require would and finally returns the new
    handler instance
*/
Vatican.prototype.loadHandler = function(path) {
    var key = new Buffer(path).toString('base64')
 
    Iif(this.handlers[key]) return this.handlers[key];
 
    var Module = module.constructor
    var m = new Module();
 
    var handlerContent = fs.readFileSync(path);
    handlerContent = handlerContent.toString().replace(/(@endpoint.+\n)/g,"//$1");
    m.paths = module.paths;
    try {
        m._compile(handlerContent, path);
        this.handlers[key] = m.exports;
    } catch (ex) {
        logger.error("Error compiling handler: ", ex)
    }
    return this.handlers[key];
};
 
/**
    Handles each request, by looking up the right handler/method to execute
*/
Vatican.prototype.requestHandler = function (req, res) { 
    logger.info("Request received: [" + req.method + "]: " + req.url);
    var self = this;
    var methodFound = this.findMethod(req.url, req.method);
    Eif( !methodFound ) {
        vaticanResp.writeNotFound(res);
    } else {
        try {
            var request = this.createRequest(req);
            var hdlr = this.loadHandler(methodFound.handlerPath);
            res = vaticanResp.improveResponse(res, request, this.options, this.postprocessors);
            //Parse the request to grab the parameters
            this.parseRequest(request, methodFound.url, req, function(newRequest) {
                var hdlrInstance = new hdlr(self.getCorrectModel(methodFound))
 
                hdlrInstance.models = self.dbmodels //Let the handler access all other models in case they're neeeded
 
                self.preprocessors.runChain({
                   req: newRequest, 
                   res: res, 
                   handler: methodFound,
                   endPrep: hdlrInstance[methodFound.action].bind(hdlrInstance),
                });
            });
        } catch (ex) {
            logger.error("Error instantiating handler: " + ex.message);
            logger.error("Stacktrace: " + ex.stack);
            res.end();
        }
    }
};
 
Vatican.prototype.getCorrectModel = function(handler) {
    var modelName = handler.handlerName.replace("Hdlr", '')
    return this.dbmodels && this.dbmodels[modelName]
}
 
/**
    Starts up the server
*/
Vatican.prototype.start = function(cb) {
    try {
        this.server = http.createServer(this.requestHandler.bind(this));
        this.server.listen(this.options.port);
        console.log(this.server);
        logger.info("Server started on port: " + this.options.port);
        Iif(typeof cb == 'function') {
            cb();
        }
    } catch (ex) {
        logger.error("Error creating server: " + ex.message);
        return false;
    }
};
 
/**
   Close the server
*/
Vatican.prototype.close = function(cb) {
    try {
        this.server.close();
        logger.info("Server closed");
        if(typeof cb == 'function') {
            cb();
        }
    } catch (ex) {
        logger.error("Error closing server: " + ex.message);
        return false;
    }
}
 
Vatican.prototype.dbStart = function(opts, cb) {
    if(typeof opts === 'function') {
        cb = opts
        opts = {}
    }
    var connString = 'mongodb://' + this.options.db.host + '/' + this.options.db.dbname
    var self = this
 
    var schemasFolder = opts.schemasFolder || process.cwd() + '/schemas'
    mongoose.connect(connString)
 
    self.dbconn = mongoose.connection
    self.dbconn.on('error', cb)
    self.dbconn.once('open', function() {
        self.loadDbModels(schemasFolder, function(err, models) {
            if(err) {
                return cb(err)
            }
            self.dbmodels = models
            cb()
        })
    })
    
}
 
Vatican.prototype.loadDbModels = function(folder, cb) {
    var models = {}
    var self = this
    fs.readdir(folder, function(err, files) {
        if(err) return cb(err)
        var path = null, tmp = null
        files.forEach(function(f) {
            path = folder + "/" + f
            tmp = require(path)(mongoose)
            models[tmp.modelName] = tmp
        })
        cb(null, models)
    })
}
 
function isAbsolutePath(p) {
  return path.resolve(p) === path.normalize(p).replace( RegExp(path.sep+'$'), '' );
}