-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroute.js
55 lines (46 loc) · 1.3 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
'use strict';
const EventEmitter = require('events');
const url = require('url');
const _ = require('lodash');
const proxy = require('http-proxy').createServer({
xfwd: true,
secure: true
});
class Route {
constructor(data) {
Object.assign(this, EventEmitter.prototype);
this.pattern = new RegExp(data.pattern);
this.methods = data.methods;
this.target = data.target;
}
accepts(method) {
return this.methods.indexOf(method) !== -1;
}
get middleware() {
return this._controller || (this._controller = Route.controller.bind(this));
}
static controller(req, res, next) {
if (!this.accepts(req.method)) { return next(); }
const target = Route.injectCapturedPatterns(
this.pattern,
req.originalUrl,
_.clone(this.target)
);
this.emit('proxy', req.method, req.originalUrl, target);
proxy.web(req, res, {
target: target,
headers: { host: this.target.host }
});
}
static injectCapturedPatterns(pattern, matchedPath, target) {
const matches = matchedPath.match(pattern);
if (matches) {
target.pathname = target.pathname.replace(/\$(\d+)/g, m => matches[m[1]]);
}
return url.format(target);
}
static get all() {
return require('./routes').map(data => new Route(data));
}
}
module.exports = Route;