flask-router-plus
Version:
Flask-inspired routing system for node and connect. Nice if you just need a routing system without depending on connect, or need routing middleware without all features provided by express.
70 lines (56 loc) • 2.19 kB
JavaScript
// Generated by CoffeeScript 1.6.3
(function() {
var RegexExtractor, RuleExtractor, defaultParser, escapeRegex,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
RegexExtractor = require('./regex-extractor');
defaultParser = require('./default-parser');
escapeRegex = function(s) {
return s.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&');
};
RuleExtractor = (function(_super) {
__extends(RuleExtractor, _super);
function RuleExtractor(parsers) {
this.parsers = parsers;
this.regexParts = ['^'];
this.params = [];
}
RuleExtractor.prototype.pushStatic = function(staticPart) {
return this.regexParts.push(escapeRegex(staticPart));
};
RuleExtractor.prototype.pushParam = function(dynamicPart) {
this.params.push(dynamicPart);
return this.regexParts.push('(.*?)');
};
RuleExtractor.prototype.compile = function() {
this.regexParts.push('$');
this.regex = new RegExp(this.regexParts.join(''));
return this;
};
RuleExtractor.prototype.extract = function(requestPath) {
var extractedArgs, i, m, param, params, parser, parsers, value, _i, _ref;
m = this.regex.exec(requestPath);
if (!m) {
return null;
}
params = this.params;
parsers = this.parsers;
extractedArgs = [];
for (i = _i = 1, _ref = m.length; 1 <= _ref ? _i < _ref : _i > _ref; i = 1 <= _ref ? ++_i : --_i) {
param = params[i - 1];
parser = parsers[param.parserName];
if (typeof parser !== 'function') {
parser = defaultParser;
}
value = parser(m[i], param.parserOpts);
if (value === null) {
return null;
}
extractedArgs[i - 1] = extractedArgs[param.name] = value;
}
return extractedArgs;
};
return RuleExtractor;
})(RegexExtractor);
module.exports = RuleExtractor;
}).call(this);