2016-11-04 16:16:55 +01:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
const { EventEmitter } = require('events');
|
2016-11-06 20:52:08 +01:00
|
|
|
const List = require('./list');
|
2016-11-04 16:16:55 +01:00
|
|
|
const moment = require('moment');
|
|
|
|
|
2016-11-06 20:52:08 +01:00
|
|
|
// this list must have entries with sorted ttl range
|
2016-11-13 20:33:23 +01:00
|
|
|
module.exports = class TTLList extends EventEmitter {
|
2016-11-06 20:52:08 +01:00
|
|
|
constructor ({
|
|
|
|
interval = 1000,
|
|
|
|
expireAmount = 1,
|
|
|
|
expireType = 'hours',
|
|
|
|
} = {}) {
|
2016-11-04 16:16:55 +01:00
|
|
|
super();
|
2016-11-13 20:33:23 +01:00
|
|
|
this.interval = interval;
|
2016-11-06 20:52:08 +01:00
|
|
|
this.expireAmount = expireAmount;
|
|
|
|
this.expireType = expireType;
|
|
|
|
|
|
|
|
this.list = new List();
|
|
|
|
|
|
|
|
this.list.on('evicted', ({ value, ttl }) => {
|
|
|
|
this.emit('expire', value, ttl);
|
|
|
|
});
|
2016-11-13 20:33:23 +01:00
|
|
|
this.startTimer();
|
|
|
|
}
|
2016-11-04 16:16:55 +01:00
|
|
|
|
2016-11-13 20:33:23 +01:00
|
|
|
startTimer () {
|
|
|
|
if (this.list) {
|
|
|
|
this.timer = setTimeout(() => {
|
|
|
|
if (this.list) {
|
|
|
|
this.timedCheck();
|
|
|
|
}
|
|
|
|
}, this.interval);
|
|
|
|
this.timer.unref();
|
|
|
|
}
|
2016-11-04 16:16:55 +01:00
|
|
|
}
|
|
|
|
|
2016-11-06 20:52:08 +01:00
|
|
|
add (value, timestamp = new Date()) {
|
|
|
|
const ttl = moment(timestamp).add(this.expireAmount, this.expireType);
|
2016-12-29 11:08:41 +01:00
|
|
|
if (moment().isBefore(ttl)) {
|
|
|
|
this.list.add({ ttl, value });
|
|
|
|
} else {
|
|
|
|
this.emit('expire', value, ttl);
|
|
|
|
}
|
2016-11-04 16:16:55 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
timedCheck () {
|
2016-12-29 11:08:41 +01:00
|
|
|
const now = moment();
|
2016-11-06 20:52:08 +01:00
|
|
|
this.list.reverseRemoveUntilTrue(({ value }) => now.isBefore(value.ttl));
|
2016-11-13 20:33:23 +01:00
|
|
|
this.startTimer();
|
2016-11-06 20:52:08 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
destroy () {
|
2016-11-13 20:33:23 +01:00
|
|
|
// https://github.com/nodejs/node/issues/9561
|
|
|
|
// clearTimeout(this.timer);
|
|
|
|
// this.timer = null;
|
2016-11-06 20:52:08 +01:00
|
|
|
this.list = null;
|
2016-11-04 16:16:55 +01:00
|
|
|
}
|
2016-11-04 23:09:50 +01:00
|
|
|
};
|