-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlayer.js
102 lines (81 loc) · 2.4 KB
/
layer.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
96
97
98
99
100
101
102
const { pathToRegexp } = require('path-to-regexp');
const { decode_param } = require('./utils')
const hasOwnProperty = Object.prototype.hasOwnProperty;
class Layer {
constructor(stack, opts = {}) {
if (!(this instanceof Layer)) {
return new Layer(path, opts);
}
this.handle = stack.handle;
this.terminate = stack.terminate;
this.$name = stack.name;
this.$domain = stack.domain;
this.$original = stack.url;
this.$methods = stack.methods;
this.$path = undefined;
this.$regexp = pathToRegexp(stack.url, this.$keys = [], opts);
this.$params = this.$keys;
this.$regexp.fast_star = stack.url === '*';
this.$regexp.fast_slash = stack.url === '/' && opts.end === false;
}
handle_error(error, ctx, next) {
var fn = this.handle;
if (fn.length !== 3) {
return next(error);
}
try {
return fn(error, ctx, next);
} catch (err) {
return next(err);
}
}
handle_request(ctx, next) {
var fn = this.handle;
ctx.request.params = this.$params;
if (fn.length > 2) {
return next();
}
try {
return fn(ctx, next);
} catch (err) {
return next(err);
}
}
match(path) {
var match;
if (path != null) {
if (this.$regexp.fast_slash) {
this.$params = {};
this.$path = '';
return true;
}
if (this.$regexp.fast_star) {
this.$params = {
'0': decode_param(path)
};
this.$path = path;
return true;
}
match = this.$regexp.exec(path);
}
if (!match) {
this.$params = undefined;
this.$path = undefined;
return false;
}
this.$params = {};
this.$path = match[0];
var keys = this.$keys;
var params = this.$params;
for (var i = 1; i < match.length; i++) {
var key = keys[i - 1];
var prop = key.name;
var val = decode_param(match[i]);
if (val !== undefined || !(hasOwnProperty.call(params, prop))) {
params[prop] = val;
}
}
return true;
}
}
module.exports = Layer;