nestjs-resilience
Version:
A module for improving the reliability and fault-tolerance of your NestJS applications
48 lines (47 loc) • 2.46 kB
JavaScript
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ThrottleStrategy = void 0;
const base_strategy_1 = require("./base.strategy");
const rxjs_1 = require("rxjs");
const exceptions_1 = require("../exceptions");
const resilience_states_manager_1 = require("../resilience.states-manager");
class ThrottleStrategy extends base_strategy_1.Strategy {
constructor(options) {
super(Object.assign(Object.assign({}, ThrottleStrategy.DEFAULT_OPTIONS), options));
if (this.options.ttl <= 0) {
throw new RangeError('TTL must be greater than 0, got: ' + this.options.ttl);
}
if (this.options.limit <= 0) {
throw new RangeError('Limit must be greater than 0, got: ' + this.options.limit);
}
}
process(observable, command) {
const cacheManager = resilience_states_manager_1.ResilienceStatesManager.getInstance();
const now = Date.now();
const expired = now - this.options.ttl;
const key = [this.name, command].join('/');
const records$ = (0, rxjs_1.from)(cacheManager.wrap(key, () => __awaiter(this, void 0, void 0, function* () { return []; }), this.options.ttl));
return records$.pipe((0, rxjs_1.switchMap)(records => {
records = records.filter(record => record >= expired);
if (records.length >= this.options.limit) {
return (0, rxjs_1.throwError)(() => new exceptions_1.ThrottlerException());
}
records = [...records, now];
return (0, rxjs_1.from)(cacheManager.set(key, records)).pipe((0, rxjs_1.switchMap)(() => observable));
}));
}
}
exports.ThrottleStrategy = ThrottleStrategy;
ThrottleStrategy.DEFAULT_OPTIONS = {
ttl: 1000,
limit: 10
};
;