-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathmanifest.js
109 lines (93 loc) · 3.13 KB
/
manifest.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
103
104
105
106
107
108
109
// @ts-check
/// <reference path="./node_modules/express-gateway/index.d.ts" />
const pathToRegExp = require('path-to-regexp');
/** @type {ExpressGateway.Plugin} */
const plugin = {
version: '1.0.0',
policies: ['rewrite'],
init: function (pluginContext) {
pluginContext.registerPolicy({
name: 'rewrite',
schema: {
$id: 'http://express-gateway.io/schemas/policies/rewrite.json',
type: 'object',
properties: {
rewrite: {
type: 'string',
description: `Express Path or RegExp corresponding to the url pattern to rewrite.
The format should match the one used in the condition.`
},
redirect: {
type: 'integer',
description: `If omitted, a rewrite action will be performed.
When set to a number, it'll redirect the request with the provided status code.`
},
}, required: ['rewrite']
},
policy: (actionParams) => {
const compiledExp = pathToRegExp.compile(actionParams.rewrite);
return (req, res, next) => {
let toUrl = null;
if (req.egContext.matchedCondition.plainRegEx)
toUrl = req.url.replace(req.egContext.matchedCondition.plainRegEx, actionParams.rewrite);
else
toUrl = decodeURIComponent(compiledExp(req.egContext.matchedCondition));
if (!actionParams.redirect) {
req.url = toUrl;
return next();
}
res.redirect(actionParams.redirect, toUrl);
}
}
});
pluginContext.registerCondition({
name: 'pathmatch',
handler: (req, conditionConfig) => {
const keys = [];
const regExpFromPath = pathToRegExp(conditionConfig.match, keys);
const extractedParameters = regExpFromPath.exec(req.url);
if (extractedParameters !== null) {
req.egContext.matchedCondition = {};
keys.forEach((key, index) => { req.egContext.matchedCondition[key.name] = extractedParameters[index + 1] });
return true;
}
return false;
},
schema: {
$id: 'http://express-gateway.io/schemas/conditions/pathmatch.json',
type: 'object',
properties: {
match: {
type: 'string',
description: 'The url pattern to look for'
}
},
required: ['match']
}
});
pluginContext.registerCondition({
name: 'regexpmatch',
handler: (req, conditionConfig) => {
const plainRegEx = new RegExp(conditionConfig.match);
const extractedParameters = plainRegEx.exec(req.url);
if (extractedParameters !== null) {
req.egContext.matchedCondition = { plainRegEx };
return true;
}
return false;
},
schema: {
$id: 'http://express-gateway.io/schemas/conditions/regexpmatch.json',
type: 'object',
properties: {
match: {
type: 'string',
description: 'The url pattern to look for'
},
},
required: ['match']
}
});
}
}
module.exports = plugin;