-
-
Notifications
You must be signed in to change notification settings - Fork 61
/
permalink.js
51 lines (43 loc) · 1.19 KB
/
permalink.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
'use strict';
const escapeRegExp = require('./escape_regexp');
const rParam = /:(\w*[^_\W])/g;
class Permalink {
constructor(rule, options) {
if (!rule) { throw new TypeError('rule is required!'); }
options = options || {};
const segments = options.segments || {};
const params = [];
const regex = escapeRegExp(rule)
.replace(rParam, (match, name) => {
params.push(name);
if (Object.prototype.hasOwnProperty.call(segments, name)) {
const segment = segments[name];
if (segment instanceof RegExp) {
return segment.source;
}
return segment;
}
return '(.+?)';
});
this.rule = rule;
this.regex = new RegExp(`^${regex}$`);
this.params = params;
}
test(str) {
return this.regex.test(str);
}
parse(str) {
const match = str.match(this.regex);
const { params } = this;
const result = {};
if (!match) { return; }
for (let i = 1, len = match.length; i < len; i++) {
result[params[i - 1]] = match[i];
}
return result;
}
stringify(data) {
return this.rule.replace(rParam, (match, name) => data[name]);
}
}
module.exports = Permalink;