Code coverage report for resourcer\lib\resourcer.js

Statements: 90.23% (120 / 133)      Branches: 72.73% (32 / 44)      Functions: 100% (23 / 23)      Lines: 90.23% (120 / 133)     

All files » resourcer\lib\ » resourcer.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 2471                 1 2       1   1 2 2     2   2           1 9   9     9     9 9     9     9 9 9   9 1 1   1         9   9 9         9 9 9 9 9       9 9 81 81 81                 1 36 36 27   9         1 9 9   9           1 93     93 93     93 93     93 93       93 93 93 93 553   275 275     93     1 27 27 27 27 27   27 27               27 54 54 54 162 162   54   27       1 9 9 9     1 81 81   1 75 66 66 66 66   66 123 66   123 123 123   123   66   66 66   9           81 75   75 72   3     6           1 123   3 3 11 8     3         1 66     1     66     1 288    
var fs = require("fs"),
	dir = require("node-dir"),
	path = require("path"),
	os = require("os"),
	deepExtend = require("node.extend"),
	xml2js = require("xml2js-expat"),
	_ = require("underscore");
 
 
module.exports = function() {
	return new Resourcer();
};
 
 
var __gR = null; //Global resources, so they're kept
 
var Resourcer = function() {
	this.load_path = "";
	this.knownFormats = {"json": "loadJsonResource", 
						 "xml": "loadXMLResource",
						 "csv": "loadCSVResource"};
	this.R = __gR || {};
	//Default options
	this.csvOpts = {
		fieldSplitter: ",",
		firstRowFieldNames: true
	};
};
 
Resourcer.prototype.init = function(opts, cb) {
	var dirname = process.cwd() + path.sep;
 
	Iif(opts.path[0] == path.sep) { //Absolute path
		this.load_path = this.normalizePath(opts.path);
	} else {
		this.load_path = opts.path = (dirname + this.normalizePath(opts.path));
	}
 
	var regExp = ".*\\" + path.sep + "$"
	var endsInSlashExp = new RegExp(regExp, "g");
 
 
	Iif(!this.load_path.match(endsInSlashExp)) 	{
		this.load_path += path.sep;
	}
	this.R = {};
	this.knownFormats = _.extend(this.knownFormats, opts.extraFormats);
	this.verbose = opts.verbose || false;
 
	if(opts.csvOpts) {
		Eif(opts.csvOpts.fieldSplitter != null) {
			this.csvOpts.fieldSplitter = opts.csvOpts.fieldSplitter;
		}
		Iif(opts.csvOpts.firstRowFieldNames != null) {
			this.csvOpts.firstRowFieldNames = opts.csvOpts.firstRowFieldNames;	
		}
	}
 
	var self = this;
 
	dir.paths(this.load_path, function(err, paths) {
		Iif(err) {
			console.log("Error reading load path: " + err);
			return;
		}
 
		var delayedCB = null;
		Eif(typeof cb == "function") {
			delayedCB = _.after(paths.files.length, function() {
				__gR = self.R; //All resources have been loaded, so updating the global object
				cb();
			});
		}
 
		var rootPath = self.load_path;
		_.each(paths.files, function(file) {
			self.loadResource(rootPath, file);
			Eif(delayedCB) {
				delayedCB();
			}
		});
		
	});
	
};
 
//JSON
Resourcer.prototype.loadJsonResource = function(content, cb) {
	try {
		var json = JSON.parse(content);
		cb(null, json);
	} catch(e) {
		cb(e, null);
	}
};
 
//XML
Resourcer.prototype.loadXMLResource = function(content, cb) {
	var p = new xml2js.Parser(function(result, error) {
			cb(error, result);
	});
	Iif(!p.parseString(content)) {
		cb(p.getError(), null);
	}
};
 
//CSV
Resourcer.prototype.splitFields = function(text) {
	text = text.replace(/""/g, "[||]"); //We change the double quotes into something different
 
	//Keep empty fields empty
	var emptyFieldPatt = new RegExp(this.csvOpts.fieldSplitter + "[\\s]*" + this.csvOpts.fieldSplitter,"g");
	text = text.replace(emptyFieldPatt, "[--]");
 
	//Keep empty fields empty
	var startEmptyFieldsPatt = new RegExp("^" + this.csvOpts.fieldSplitter,"g");
	text = text.replace(startEmptyFieldsPatt, "[--]" + this.csvOpts.fieldSplitter);
 
	//Keep empty fields empty
	var endEmptyFieldPatt = new RegExp(this.csvOpts.fieldSplitter + "$","g");
	text = text.replace(endEmptyFieldPatt, this.csvOpts.fieldSplitter + "[--]");
 
 
	//RegExp that'll split the fields accordingly
	var patt = new RegExp('"([^"]*)"|([^"' + this.csvOpts.fieldSplitter + ']*)', "g");
	var matches = text.match(patt);
	var self = this;
	var parts = _.filter(matches,function(m) {
		return (m.trim().length > 0 && m.trim() != self.csvOpts.fieldSplitter);
	}).map(function(m) {
		m = m.replace(/"/g, "").replace(/\[\|\|\]/g, '"').replace(/\[--\]/, ""); //Remove single quotes and add the required single quotes
		return m.trim();
	});
 
	return parts;
};
 
Resourcer.prototype.loadCSVResource = function(content, cb) {
	var rows = content.split(os.EOL);
	var self = this;
	var startingRow = 0;
	var fieldNames = this.splitFields(rows[0]);
		results = [];
 
	Eif(this.csvOpts.firstRowFieldNames) {
		startingRow = 1;
	} else {
		var rowCount = fieldNames.length;
		fieldNames = [];
		for(var i = 0; i < rowCount; i++) {
			fieldNames.push("field" + i);
		}
	}
	for(var i = startingRow; i < rows.length; i++) {
		var cols = this.splitFields(rows[i]);
		var tmpDummy = {};
		_.each(fieldNames, function(name, idx) {
			var fieldName = self.sanitizeString(name).trim();
			tmpDummy[fieldName] = (cols[idx]) ? cols[idx].trim() : "";
		});
		results.push(tmpDummy);
	}
	cb(null, results);
};
 
 
Resourcer.prototype.normalizePath = function(p) {
	p = p.replace(/\//g, path.sep);
	p = p.replace(/\\/g, path.sep);
	return p;
};
 
Resourcer.prototype.loadResource = function(rootPath, filePath) {
	var ext = path.extname(filePath).replace(".","");
	var self = this;
 
	function processLoadedResource(err, json) {
		if(!err) {
			var relativePath = filePath.replace(rootPath, "");
			var relPathParts = relativePath.split(path.sep);
			var focus = {};
			var jsonParent = focus;
 
			_.each(relPathParts, function(part) {
				if(part.indexOf(".") != -1) {
					part = path.basename(part, ext);
				}
				part = self.sanitizeString(part);
				Eif(!focus[part]) {
					focus[part] = self.makePathNode(); 
				}
				focus = focus[part];
			});
			var resource = self.makeResource(json, resourceContent);
 
			focus = _.extend(focus, resource);
			self.R = deepExtend(true, self.R, jsonParent);
		} else {
			Iif(self.verbose) {
				console.log("Invalid format for resource: " + filePath);
				console.log(err);
			}
		}
	}
	if(this.knownFormats[ext]) {
		var resourceContent = fs.readFileSync(filePath, "utf8");
 
		if(typeof this.knownFormats[ext] == "string") {
			this[this.knownFormats[ext]](resourceContent, processLoadedResource);
		} else {
			this.knownFormats[ext](resourceContent, processLoadedResource);
		}
	} else {
		Iif(self.verbose) {
			console.log("Unkown format, so ignoring resource: " + filePath);
		}
	}
};
 
Resourcer.prototype.makePathNode = function() {
	return {
		listResources: function() {
			var list = [];
			for(prop in this) {
				if(typeof this[prop] != "function") {
					list.push(prop);
				}
			}
			return list;
		}
	}
};
 
Resourcer.prototype.makeResource = function(json, original) {
	var methods = {
		original_content: original,
		original: function() {
			return this.original_content;
		}
	}	
	return _.extend(json, methods);
};
 
Resourcer.prototype.sanitizeString = function(str) {
	return str.replace(/[ -]+/g, "_").replace(/[\/><\\:*\|\"!\.]+/g, "");
};