dino-express
Version:
DinO enabled REST framework based on express
62 lines • 2.23 kB
JavaScript
;
// Copyright 2018 Quirino Brizi [quirino.brizi@gmail.com]
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.RateLimitPolicy = void 0;
const AbstractPolicy_1 = require("./AbstractPolicy");
const dino_core_1 = require("dino-core");
/**
* Allows to control the number of requests received by the API in the time
* interval
*/
class RateLimitPolicy extends AbstractPolicy_1.AbstractPolicy {
configuration;
buckets;
constructor() {
super();
this.buckets = new Map();
}
apply(req) {
const now = Date.now();
const key = (req.headers['x-forwarded-for'] ?? req.socket.remoteAddress);
const weight = 1;
const windowSize = this.configuration.interval / 1000 / this.configuration.allow;
let allowed = true;
let bucket = this.buckets.get(key);
if (bucket === undefined) {
bucket = { used: 0, windowExpires: 0 };
this.buckets.set(key, bucket);
}
dino_core_1.Logger.debug('Bucket', bucket);
if (now < bucket.windowExpires) {
bucket.used = bucket.used + weight;
allowed = false;
}
else {
this.buckets.set(key, bucket);
bucket.windowExpires = now + weight * windowSize;
bucket.used = weight;
}
return allowed;
}
configure(configuration) {
this.configuration = configuration;
}
onDeny(res) {
res.status(429);
res.body = { message: 'Too Many Requests' };
}
}
exports.RateLimitPolicy = RateLimitPolicy;
//# sourceMappingURL=RateLimitPolicy.js.map