-
Notifications
You must be signed in to change notification settings - Fork 1
/
bundler.js
64 lines (50 loc) · 1.32 KB
/
bundler.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
const Route = require('./route');
class Bundler {
constructor () {
this.matchers = [];
}
set (uri, bundle) {
this.matchers.push(new BundlerMatcher(uri, bundle));
}
match (ctx) {
return this.matchers.find(matcher => matcher.match(ctx));
}
async delegate (ctx) {
const matches = this.match(ctx);
if (!matches) {
return false;
}
await matches.bundle.dispatch(matches, ctx);
return true;
}
}
class BundlerMatcher {
constructor (uri, bundle) {
this.uri = uri;
this.bundle = bundle;
this.isStatic = Route.isStatic(uri);
if (!this.isStatic) {
[this.pattern, this.args] = Route.parse(`(${this.uri})[(.+)]`);
}
}
match (ctx) {
if (this.isStatic) {
const uri = this.uri === '/' ? '/' : this.uri + '/';
return ctx.path === this.uri || ctx.path.startsWith(uri);
}
const result = ctx.path.match(this.pattern);
if (result) {
ctx.parameters = Object.assign(ctx.parameters, Route.fetchParams(result, this.args));
return true;
}
return false;
}
shiftPath (ctx) {
if (this.isStatic) {
return this.uri === '/' ? ctx.path : ctx.path.substr(this.uri.length) || '/';
}
const matches = ctx.path.match(this.pattern);
return ctx.path.substr(matches[1].length) || '/';
}
}
module.exports = Bundler;