root.js 6.62 KB
Newer Older
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 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
/*jshint node:true*/
"use strict";

var utils = require("./utils");

var regexpSlashes = /\//g,
	regexpTrimSlashes = /^\/|\/$/g,
	regexpTrailingStar = /\*$/,
	regexpAllNamedParameters = /:[^\/]+/g;




/*!
 * Generic helpers
 */


var compiledCache = {};
function compilePattern(pattern, matchSubPaths) {
	var cacheKey = matchSubPaths ? pattern + "[/*]" : pattern;

	if (!(cacheKey in compiledCache)) {
		var compiled = {
			raw: pattern,
			key: cacheKey
		};

		var regexp = "^\\/" + pattern
				.replace(regexpSlashes, "\\/")
				.replace(regexpAllNamedParameters, "([^\\/]+)")
				.replace(regexpTrailingStar, "(.*)$");

		compiled.trailingStar = !!(pattern.match(regexpTrailingStar));

		if (!compiled.trailingStar && matchSubPaths) {
			compiled.regexp = new RegExp(regexp + "(\\/.*)?$");
		} else {
			compiled.regexp = new RegExp(compiled.trailingStar ? regexp : (regexp + "$"));
		}

		compiled.names = (pattern.match(regexpAllNamedParameters) || []).map(function(name) {
			return name.substr(1);
		});

		if (compiled.trailingStar) {
			compiled.names.push("*");
		}

		compiledCache[cacheKey] = compiled;
	}

	return compiledCache[cacheKey];
}


function addHandler(handlers, compiled, method, handler) {
	var item = Object.create(compiled);

	item.method = method;
	item.handler = handler;
	handlers.push(item);

	return item;
}


function addHook(handlers, compiled, hook, strict) {
	if (!strict && !compiled.trailingStar) {
		compiled = compilePattern(compiled.raw, true);
	}

	var item = Object.create(compiled);

	item.hook = hook;
	handlers.push(item);

	return item;
}


function addOptions(handlers, compiled, options) {
	var item = Object.create(compiled);

	item.options = options;
	handlers.push(item);

	return item;
}



/*!
 * Path matcher
 */


function Path(root, pattern) {
	this.root = root;
	this.compiled = compilePattern(pattern);

	if (this.compiled.trailingStar) {
		this.sub = undefined;
		this.remove = undefined;
	}
}


"get list count post put del".split(" ").forEach(function(method) {
	Path.prototype[method] = function(handler) {
		addHandler(this.root.handlers, this.compiled, method, handler);
		return this;
	};
});


Path.prototype.hook = function(hook, strict) {
	addHook(this.root.handlers, this.compiled, hook, strict);
	return this;
};


Path.prototype.readonly = function(subsToo) {
	var path = this;

	"post put del".split(" ").forEach(function(method) {
		path[method](undefined);
		if (subsToo) {
			path.sub("*")[method](undefined);
		}
	});

	return this;
};


Path.prototype.sub = function(pattern, hook) {
	pattern = pattern.replace(regexpTrimSlashes, "");
	return this.root.sub(this.compiled.raw + "/" + pattern, hook);
};


Path.prototype.remove = function(pattern) {
	pattern = pattern.replace(regexpTrimSlashes, "");
	return this.root.remove(this.compiled.raw + "/" + pattern);
};


Path.prototype.set = function(key, value, strict) {
	if (typeof key === "object") {
		strict = value;
	}

	var compiled = this.compiled;
	if (!strict && !compiled.trailingStar) {
		compiled = compilePattern(compiled.raw, true);
	}

	var hook = this.root.handlers.filter(function(h) {
		return h.options && h.raw === compiled.raw;
	})[0];

	if (!hook) {
		hook = addOptions(this.root.handlers, compiled, {});
	}

	if (typeof key === "object") {
		Object.keys(key).forEach(function(k) {
			hook.options[k] = key[k];
		});
	} else {
		hook.options[key] = value;
	}

	return this;
};



/*!
 * Base hooks
 */


function getParamHook(names, match) {
	// Strip full match
	var values = match.slice(1);

	return function paramHook(req, next) {
		req.params = req.params || {};
		names.forEach(function(name) {
			var value = values.shift();

			if (name === "*") {
				req.params[name] = value;
			} else {
				req.params[name] = decodeURIComponent(value);
			}
		});

		next();
	};
}


function getOptionsHook() {
	var hook = function optionsHook(req, next) {
		req.options = req.options || {};

		Object.keys(hook.options).forEach(function(key) {
			req.options[key] = hook.options[key];
		});

		next();
	};

	hook.options = {};

	return hook;
}


function getHref(subpath) {
	/*jshint validthis:true */
	var req = this;
	var path = req.path.replace(regexpTrimSlashes, "");

	if (subpath) {
		path = path + "/" + subpath.replace(regexpTrimSlashes, "");
	}

	return utils.getHref(req, path);
}


function matchPattern(pattern, path) {
	/*jshint validthis:true */
	var compiled = compilePattern(pattern);
	var req = this;

	var match = (path || req.path).match(compiled.regexp);

	if (match) {
		var values = match.slice(1);
		var params = {};

		compiled.names.forEach(function(name) {
			params[name] = values.shift();
		});

		return params;
	}

	return false;
}


var defaultHooks = [
	/* Add request helpers */
	function requestHelpersHook(req, next) {
		req.getHref = getHref;
		req.match = matchPattern;

		next();
	}
];



/*!
 * Root resource
 */

function rootResource() {
	var root = {
		handlers: [],

		sub: function(pattern, hook) {
			var path = new Path(root, pattern.replace(regexpTrimSlashes, ""));

			if (hook) {
				path.hook(hook);
			}

			return path;
		},

		remove: function(pattern) {
			pattern = pattern.replace(regexpTrimSlashes, "");

			function filterFunc(h) {
				var raw = h.raw;

				if (raw.substr(0, pattern.length) === pattern) {
					if (raw.length === pattern.length || raw[pattern.length] === "/") {
						return false;
					}
				}

				return true;
			}

			root.handlers = root.handlers.filter(filterFunc);
		},

		match: function(req) {
			var matchingHooks = defaultHooks.slice(0);
			var spec = {};
			var matchedPatterns = [];

			/* Add options hook */
			var optionsHook = getOptionsHook();
			matchingHooks.push(optionsHook);

			/* Find handlers matching requested path */
			root.handlers.forEach(function(h) {
				var match = req.path.match(h.regexp);

				if (match) {
					/* Add parameter hook only once for each pattern */
					if (h.names.length > 0 && matchedPatterns.indexOf(h.raw) === -1) {
						matchingHooks.push(getParamHook(h.names, match));
						matchedPatterns.push(h.raw);
					}

					if (h.options) {
						var options = optionsHook.options;
						Object.keys(h.options).forEach(function(key) {
							options[key] = h.options[key];
						});
					}

					if (h.hook) {
						matchingHooks.push(h.hook);
					}

					if (h.method) {
						// get and count/list override each other
						if (h.method === "get") {
							delete spec.count;
							delete spec.list;
						}

						if (h.method === "count" || h.method === "list") {
							delete spec.get;
						}

						spec[h.method] = h.handler;
					}
				}
			});

			if (Object.keys(spec).length) {
				return { spec: spec, hooks: matchingHooks };
			}
		}
	};

	return root;
}


module.exports = rootResource;