From 9768b9e2cf26479be695abdfa1f0c8d8cb778f76 Mon Sep 17 00:00:00 2001 From: Stanislav Mishchyshyn Date: Fri, 7 Feb 2025 16:48:13 +0200 Subject: [PATCH] fix: provide compatibility when running code in vm.runInNewContext() --- src/app/utils/TtlCache.ts | 8 ++++++++ test/app/TtlCache.spec.ts | 12 ++++++++++++ 2 files changed, 20 insertions(+) diff --git a/src/app/utils/TtlCache.ts b/src/app/utils/TtlCache.ts index 6d12875..76a8468 100644 --- a/src/app/utils/TtlCache.ts +++ b/src/app/utils/TtlCache.ts @@ -61,6 +61,14 @@ export class TtlCache { } private scheduleCleanup(): void { + /** + * Required due to source code evaluation in vm context compatibility + * Temporary workaround until for internal needs + * Should be removed soon + */ + if (typeof setTimeout !== 'function') { + return; + } this.timeoutId = setTimeout(() => this.cleanup(), this.cleanupInterval); this.timeoutId.unref?.(); } diff --git a/test/app/TtlCache.spec.ts b/test/app/TtlCache.spec.ts index ffec297..51794ac 100644 --- a/test/app/TtlCache.spec.ts +++ b/test/app/TtlCache.spec.ts @@ -4,13 +4,16 @@ import sinon from 'sinon'; describe('TtlCache', () => { let clock: sinon.SinonFakeTimers; + let setTimeoutBackup: typeof setTimeout; beforeEach(() => { + setTimeoutBackup = global.setTimeout; clock = sinon.useFakeTimers(); }); afterEach(() => { clock.restore(); + global.setTimeout = setTimeoutBackup; }); it('should set and get a value', () => { @@ -68,4 +71,13 @@ describe('TtlCache', () => { clock.tick(500); // Trigger cleanup expect(cache.get('key1')).to.be.undefined; }); + + it('should not schedule cleanup if setTimeout is not available', () => { + const cache = new TtlCache({ ttl: 1000, cleanupInterval: 500 }); + global.setTimeout = undefined as any; + cache.set('key1', 123); + expect(cache.get('key1')).to.equal(123); + clock.tick(1001); + expect(cache.get('key1')).to.equal(123); + }); });