zcatalyst-cli
Version:
Command Line Tool for CATALYST
47 lines (46 loc) • 1.75 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = (_REQ, res, next) => {
if (res.locals.apigRules === undefined) {
next(new Error('INVALID_URL'));
return;
}
const matchedRules = res.locals.apigRules;
let bestRule = matchedRules[0];
let maxPartLength = -1;
bestRule = matchedRules.reduce((accumulator, rule) => {
let setAsBest = false;
const partsLength = rule.source_endpoint.split('/').length;
if (partsLength === maxPartLength) {
const currentGrpCount = rule.source_endpoint.split('/').reduce((count, part) => {
return part.startsWith(':') ? ++count : count;
}, 0);
const prevGrpCount = accumulator.source_endpoint.split('/').reduce((count, part) => {
return part.startsWith(':') ? ++count : count;
}, 0);
if (currentGrpCount < prevGrpCount) {
setAsBest = true;
maxPartLength = partsLength;
}
else if (currentGrpCount === prevGrpCount) {
const currentTotalLen = rule.source_endpoint.length;
const prevTotalLen = accumulator.source_endpoint.length;
if (currentTotalLen < prevTotalLen) {
setAsBest = true;
maxPartLength = partsLength;
}
}
}
else if (partsLength > maxPartLength) {
setAsBest = true;
maxPartLength = partsLength;
}
if (setAsBest) {
accumulator = rule;
}
return accumulator;
}, bestRule);
res.locals.bestRule = bestRule;
delete res.locals.apigRules;
next();
};