node-web-mvc
Version:
node spring mvc
56 lines (55 loc) • 2.01 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const IllegalMappingPatternError_1 = __importDefault(require("../../errors/IllegalMappingPatternError"));
const cache = new Map();
class PathPattern {
/**
* 以缓存方式创建一个路径模式匹配实例
* @param pattern
*/
static create(pattern) {
if (!cache.get(pattern)) {
cache.set(pattern, new PathPattern(pattern));
}
return cache.get(pattern);
}
constructor(pattern) {
let parameterIndex = 1;
this.pattern = pattern;
this.parameters = {};
const doubleWildIndex = pattern.indexOf('**');
if (doubleWildIndex > -1 && doubleWildIndex !== pattern.length - 2) {
throw new IllegalMappingPatternError_1.default(pattern);
}
const holder = String.fromCharCode(0);
const express = pattern
// 双通配符,需要支持 /多级匹配
.replace(/\*\*/, holder)
// 支持单通配符 *
.replace(/\*/g, '[^/]*')
// 支持变量 {id} {id:\\d+}
.replace(/{([^}]+)}/g, (_, name) => {
const [key, content] = name.split(':');
this.parameters[parameterIndex++] = key;
return `(${content || '[^/]*'})`;
})
.replace(holder, '.*');
this.regexp = new RegExp(`^${express}$`);
}
match(path) {
const result = { matched: false, params: {} };
const values = path.match(this.regexp);
values === null || values === void 0 ? void 0 : values.forEach((value, i) => {
const name = this.parameters[i];
if (name) {
result.params[name] = value;
}
});
result.matched = !!values;
return result;
}
}
exports.default = PathPattern;