diff --git a/server/utils.js b/server/utils.js index 2fa81bdf7296635891b759782d2d5e5a93d124bf..0716563e9fb2361df198888890de647cfe70f282 100644 --- a/server/utils.js +++ b/server/utils.js @@ -2,23 +2,57 @@ const jwt = require('jsonwebtoken'); const { cert } = require('./config'); -const interval = (fn, initialTTL, output = { id: null, clear: () => undefined }) => { - const timeoutID = setTimeout(async () => { - let TTL; - try { - TTL = fn(); - if (TTL instanceof Promise) { - TTL = await TTL; +const initialOutput = { id: null, clear: () => undefined, trigger: () => undefined }; + +const replace = (toReplace, replacer) => { + Object.keys(replacer).forEach((x) => { + toReplace[x] = replacer[x]; + }); +}; + +function Timeout(fn, interval) { + this.id = setTimeout(fn, interval); + this.cleared = false; + this.clear = () => { + this.cleared = true; + clearTimeout(this.id); + }; +} + +const interval = (fn, initialTTL, output = initialOutput) => { + const getTimeout = ttl => + new Timeout(async () => { + let TTL; + try { + if (this.cleared) { + return; + } + TTL = fn(); + if (TTL instanceof Promise) { + TTL = await TTL; + } + } catch (error) { + console.error(error); + TTL = initialTTL; + } + if (this.cleared) { + return; } - } catch (error) { - console.error(error); - TTL = initialTTL; - } - const nextTTL = parseInt(TTL, 10) || initialTTL; - interval(fn, nextTTL, output); - }, initialTTL); - output.id = timeoutID; - output.clear = () => clearTimeout(timeoutID); + const nextTTL = parseInt(TTL, 10) || initialTTL; + interval(fn, nextTTL, output); + }, ttl); + const getOutput = timeout => ({ + id: timeout.id, + clear: () => timeout.clear(), + trigger: () => { + timeout.clear(); + const newTimeout = getTimeout(0); + replace(output, getOutput(newTimeout)); + }, + }); + + const timeout = getTimeout(initialTTL); + replace(output, getOutput(timeout)); return output; };