-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
75 lines (65 loc) · 1.62 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
/**
* Little module to launch a function at a specific delay.
*/
'use strict'
const MAX_TIME_INTERVAL = 60000
class Reloader {
/**
* Constructor of the class
*/
constructor (delay) {
this.config_loaded = false
this.content = {}
this.functions = {}
this.delay = delay || MAX_TIME_INTERVAL
}
/**
* Set the interval timer
*/
async init () {
if (this.content_loaded) return this.content
this.content_loaded = true
await this.retrieve()
this.timer = setInterval(this.retrieve.bind(this), this.delay)
return this.content
}
/**
* Add a new function
*
* @param {String} name: function's name
* @param {Function} fn : function to run
* @param {Number} delay : delay in ms between each run
*/
addFunction (name, fn, delay) {
this.functions[name] = { delay: delay || this.delay, fn: fn, lastUpdate: 0 }
}
/**
* Get the result of a specific function
*
*/
get (name) {
return this.content[name]
}
/**
* Get all last results of all functions
*
*/
getAll () {
return this.content
}
/**
* Check the age of each functions and rerun it if necessary
*
*/
async retrieve () {
const now = new Date()
for (const key in this.functions) {
const currentFn = this.functions[key]
if (now - currentFn.lastUpdate > this.delay) {
this.content[key] = await currentFn.fn()
currentFn.lastUpdate = new Date()
}
}
}
}
module.exports = Reloader