jai-server
Version:
Fast , simple and powerful web framework for creating REST APIs for your next project. RESTFul API server
29 lines (28 loc) • 1.07 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const CATCH_ROUTES_REGEX = /(\*)|(:([a-zA-Z_0-9$]+))/g;
const TRAILING_SLASH_REGEX = /\/$/;
const EMPTY_STRING = '';
function Matcher(q = '', url = '', fullMatch = false, strict = false) {
if (q.indexOf(':') === -1 && q === url)
return true;
const query = strict ? q : q.replace(TRAILING_SLASH_REGEX, EMPTY_STRING);
const params = {};
const finalQuery = query.replace(CATCH_ROUTES_REGEX, (_, wildcard, __, param) => {
if (param) {
params[param] = EMPTY_STRING;
return '([^\\/]+)';
}
return wildcard ? '(?:(?:.)*)' : _;
});
const matchRegex = new RegExp(`${fullMatch ? '^' : ''}${finalQuery}${strict ? '' : '\\/?'}${fullMatch ? '$' : ''}`);
const matched = url.match(matchRegex);
if (!matched)
return false;
const paramsKeys = Object.keys(params);
for (let i = 1; i < matched.length; i++) {
params[paramsKeys[i - 1]] = matched[i];
}
return params;
}
exports.default = Matcher;