Skip to content

Commit

Permalink
fix: provide compatibility when running code in vm.runInNewContext()
Browse files Browse the repository at this point in the history
  • Loading branch information
stas-nc committed Feb 7, 2025
1 parent 6996be0 commit 9768b9e
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/app/utils/TtlCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,14 @@ export class TtlCache<K, V> {
}

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?.();
}
Expand Down
12 changes: 12 additions & 0 deletions test/app/TtlCache.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down Expand Up @@ -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<string, number>({ 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);
});
});

0 comments on commit 9768b9e

Please sign in to comment.