-
Notifications
You must be signed in to change notification settings - Fork 1
/
route.js
95 lines (81 loc) · 2.1 KB
/
route.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
class Route {
static parse (str) {
const chunks = str.split('[');
if (chunks.length > 2) {
throw new Error('Invalid use of optional params');
}
const [chunk, restChunk] = chunks;
const tokens = [];
const re = chunk.replace(/{([^}]+)}/g, function (g, token, i) {
while (i >= 0) {
const current = chunk[i];
if (current === '}') {
break;
}
if (current === ':' && i >= 2 && chunk.substr(i - 2, 3) === '(?:') {
i = i - 3;
continue;
}
if (current === '(') {
tokens.push('');
}
i--;
}
tokens.push(token);
return '([^/]+)';
}).replace(/\//g, '\\/');
let optRe = '';
if (restChunk) {
optRe = '(?:' + restChunk.slice(0, -1).replace(/{([^}]+)}/g, function (g, token) {
tokens.push(token);
return '([^/]+)';
}).replace(/\//g, '\\/') + ')?';
}
return [new RegExp('^' + re + optRe + '$'), tokens];
}
static isStatic (uri) {
return !uri.match(/[[{]/);
}
constructor (uri, callback) {
this.uri = uri;
this.callback = callback;
this.isStatic = Route.isStatic(uri);
if (!this.isStatic) {
[this.pattern, this.args] = Route.parse(this.uri);
}
}
static fetchParams (result = [], args = []) {
return result.reduce((params, token, index) => {
params[index] = token;
return params;
}, args.reduce((params, name, index) => {
if (name) {
params[name] = decodeURIComponent(result[index + 1]);
}
return params;
}, {}));
}
match (ctx) {
if (this.isStatic) {
if (ctx.path === this.uri) {
return true;
}
} else {
const result = ctx.path.match(this.pattern);
if (result) {
ctx.parameters = Object.assign(ctx.parameters, Route.fetchParams(result, this.args));
return true;
}
}
return false;
}
async dispatch (ctx) {
ctx.status = 200;
const result = await this.callback(ctx);
if (result === undefined) {
return;
}
ctx.state.result = result;
}
}
module.exports = Route;