-
Notifications
You must be signed in to change notification settings - Fork 3
/
express-middleware.html
129 lines (107 loc) · 3.36 KB
/
express-middleware.html
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
<script>
class ExpressMiddleware extends HTMLElement {
constructor() {
super();
this.method = null;
this.path = null;
this.callback = null;
this.callbacks = null;
this.app = null;
this.router = null;
this.route = null;
}
static get observedAttributes() {
return [
'method',
'path'
];
}
attributeChangedCallback(name, oldValue, newValue) {
switch (name) {
case 'method': {
this.method = newValue;
break;
}
case 'path': {
this.path = newValue;
break;
}
}
}
expressReadyCallback(app, express, router, route) {
this.app = app;
this.router = router;
this.route = route;
if (this.callback) {
this.initRouteWithCallback();
return;
}
if (this.callbacks) {
this.initRouteWithCallbacks();
return;
}
}
initRouteWithCallback() {
if (this.method) {
if (!this.path) {
throw 'ExpressMiddlewareError: specifying a method requires specifying a path';
}
if (this.route) {
this.route[this.method.toLowerCase()](this.callback);
}
else if (this.router) {
this.router[this.method.toLowerCase()](this.path, this.callback);
}
else {
this.app[this.method.toLowerCase()](this.path, this.callback);
}
return;
}
if (this.path) {
if (this.router) {
this.router.use(this.path, this.callback);
}
else {
this.app.use(this.path, this.callback);
}
return;
}
if (this.router) {
this.router.use(this.callback);
}
else {
this.app.use(this.callback);
}
}
initRouteWithCallbacks() {
if (this.method) {
if (this.route) {
this.route[this.method.toLowerCase()](...this.callbacks);
}
else if (this.router) {
this.router[this.method.toLowerCase()](this.path, ...this.callbacks);
}
else {
this.app[this.method.toLowerCase()](this.path, ...this.callbacks);
}
return;
}
if (this.path) {
if (this.router) {
this.router.use(this.path, ...this.callbacks);
}
else {
this.app.use(this.path, ...this.callbacks);
}
return;
}
if (this.router) {
this.router.use(...this.callback);
}
else {
this.app.use(...this.callback);
}
}
}
window.customElements.define('express-middleware', ExpressMiddleware);
</script>