1 | "use strict";
|
2 | var __importDefault = (this && this.__importDefault) || function (mod) {
|
3 | return (mod && mod.__esModule) ? mod : { "default": mod };
|
4 | };
|
5 | const escape_regexp_1 = __importDefault(require("./escape_regexp"));
|
6 | const rParam = /:(\w*[^_\W])/g;
|
7 | class Permalink {
|
8 | constructor(rule, options) {
|
9 | if (!rule) {
|
10 | throw new TypeError('rule is required!');
|
11 | }
|
12 | options = options || {};
|
13 | const segments = options.segments || {};
|
14 | const params = [];
|
15 | const regex = (0, escape_regexp_1.default)(rule)
|
16 | .replace(rParam, (match, name) => {
|
17 | params.push(name);
|
18 | if (Object.prototype.hasOwnProperty.call(segments, name)) {
|
19 | const segment = segments[name];
|
20 | if (segment instanceof RegExp) {
|
21 | return segment.source;
|
22 | }
|
23 | return segment;
|
24 | }
|
25 | return '(.+?)';
|
26 | });
|
27 | this.rule = rule;
|
28 | this.regex = new RegExp(`^${regex}$`);
|
29 | this.params = params;
|
30 | }
|
31 | test(str) {
|
32 | return this.regex.test(str);
|
33 | }
|
34 | parse(str) {
|
35 | const match = str.match(this.regex);
|
36 | const { params } = this;
|
37 | const result = {};
|
38 | if (!match) {
|
39 | return;
|
40 | }
|
41 | for (let i = 1, len = match.length; i < len; i++) {
|
42 | result[params[i - 1]] = match[i];
|
43 | }
|
44 | return result;
|
45 | }
|
46 | stringify(data) {
|
47 | return this.rule.replace(rParam, (match, name) => data[name]);
|
48 | }
|
49 | }
|
50 | module.exports = Permalink;
|
51 |
|
\ | No newline at end of file |