-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
113 lines (83 loc) · 3.21 KB
/
index.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
110
111
112
113
/*global module,require*/
(function limitdHapiPlugin(module, require) {
'use strict';
const packageInformation = require('./package.json')
, joi = require('joi')
, optionsSchema = joi.object().keys({
'endpoint': joi.string().min(15).required(),
'bucket': joi.string().min(3).required(),
'inRequestKey': joi.string().min(3).required()
}).with('endpoint', 'bucket', 'inRequestKey')
, LimitdClient = require('limitd-client')
, parseRequestForKey = function parseRequestForKey(request, inRequestKey) {
let partial = request;
inRequestKey.split('.').forEach(element => {
if (partial &&
partial[element]) {
partial = partial[element];
} else {
partial = undefined;
}
});
return partial;
}
, limitdHapiPluginObject = (server, options, next) => {
if (options) {
joi.validate(options, optionsSchema, (err, value) => {
if (err) {
return next(new Error(err));
}
const limitd = new LimitdClient(value.endpoint);
server.ext('onPreResponse', (request, reply) => {
if (request.headers &&
request.headers['X-RateLimit-Limit'] &&
request.headers['X-RateLimit-Remaining'] &&
request.headers['X-RateLimit-Reset']) {
request.response.header('X-RateLimit-Limit', request.headers['X-RateLimit-Limit']);
request.response.header('X-RateLimit-Remaining', request.headers['X-RateLimit-Remaining']);
request.response.header('X-RateLimit-Reset', request.headers['X-RateLimit-Reset']);
}
reply.continue();
});
server.ext('onPostAuth', (request, reply) => {
if (request.route.settings.plugins &&
!request.route.settings.plugins.limitd) {
return reply.continue();
}
let valueInRequest = parseRequestForKey(request, value.inRequestKey);
if (!valueInRequest) {
return reply({
'cause': `request.${value.inRequestKey} does not exists`
}).code(502);
}
limitd.take(value.bucket, String(valueInRequest), (limitdErr, limitdResponse) => {
if (limitdErr) {
return reply({
'cause': `limitd error: ${limitdErr.message}`
}).code(502);
}
request.headers = request.headers || {};
request.headers['X-RateLimit-Limit'] = limitdResponse.limit;
request.headers['X-RateLimit-Remaining'] = limitdResponse.remaining;
request.headers['X-RateLimit-Reset'] = limitdResponse.reset;
if (limitdResponse.conformant) {
return reply.continue();
}
reply()
.code(429);
});
});
next();
});
} else {
next(new Error(`You must specify the options`));
}
};
limitdHapiPluginObject.attributes = {
'name': packageInformation.name,
'version': packageInformation.version
};
module.exports = {
'register': limitdHapiPluginObject
};
}(module, require));