UNPKG

bottleneck

Version:

Distributed task scheduler and rate limiter

113 lines (97 loc) 3.45 kB
"use strict"; function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } // Generated by CoffeeScript 2.2.4 (function () { var Events, Group, parser; parser = require("./parser"); Events = require("./Events"); Group = function () { class Group { constructor(limiterOptions = {}, groupOptions = {}) { this.key = this.key.bind(this); this.deleteKey = this.deleteKey.bind(this); this.limiters = this.limiters.bind(this); this.keys = this.keys.bind(this); this._startAutoCleanup = this._startAutoCleanup.bind(this); this.updateSettings = this.updateSettings.bind(this); this.limiterOptions = limiterOptions; parser.load(groupOptions, this.defaults, this); this.Events = new Events(this); this.instances = {}; this.Bottleneck = require("./Bottleneck"); this._startAutoCleanup(); } key(key = "") { var ref; return (ref = this.instances[key]) != null ? ref : (() => { var limiter; limiter = this.instances[key] = new this.Bottleneck(Object.assign(this.limiterOptions, { id: `group-key-${key}`, _groupTimeout: this.timeout })); this.Events.trigger("created", [limiter, key]); return limiter; })(); } deleteKey(key = "") { var ref; if ((ref = this.instances[key]) != null) { ref.disconnect(); } return delete this.instances[key]; } limiters() { var k, ref, results, v; ref = this.instances; results = []; for (k in ref) { v = ref[k]; results.push({ key: k, limiter: v }); } return results; } keys() { return Object.keys(this.instances); } _startAutoCleanup() { var _this = this; var base; clearInterval(this.interval); return typeof (base = this.interval = setInterval(_asyncToGenerator(function* () { var e, k, ref, results, time, v; time = Date.now(); ref = _this.instances; results = []; for (k in ref) { v = ref[k]; try { if (yield v._store.__groupCheck__(time)) { results.push(_this.deleteKey(k)); } else { results.push(void 0); } } catch (error) { e = error; results.push(v.Events.trigger("error", [e])); } } return results; }), this.timeout / 2)).unref === "function" ? base.unref() : void 0; } updateSettings(options = {}) { parser.overwrite(options, this.defaults, this); if (options.timeout != null) { return this._startAutoCleanup(); } } }; Group.prototype.defaults = { timeout: 1000 * 60 * 5 }; return Group; }.call(this); module.exports = Group; }).call(undefined);