diff --git a/src/gateway/Cache.ts b/src/gateway/Cache.ts index a039afb5..4c659810 100644 --- a/src/gateway/Cache.ts +++ b/src/gateway/Cache.ts @@ -4,7 +4,7 @@ export default class Cache { store: Store; constructor(store: Store = {}) { - this.store = store; + this.store = Object.freeze(store); } get(key: string) { @@ -19,15 +19,17 @@ export default class Cache { } set(key: string, val: unknown, exp = 86400000, now = new Date().getTime()) { - this.store[key] = { - val, - exp: exp + now, - }; - this.expire(); + return new Cache({ + ...this.store, + [key]: { + val, + exp: exp + now, + }, + }).expire(); } private expire() { - this.store = this.expireMany(this.store, 20); + return new Cache(this.expireMany(this.store, 20)); } private expired(store: Store, key: string, now = new Date().getTime()) { diff --git a/src/gateway/HttpGateway.ts b/src/gateway/HttpGateway.ts index 4fd98f24..cb4e2e2c 100644 --- a/src/gateway/HttpGateway.ts +++ b/src/gateway/HttpGateway.ts @@ -13,7 +13,7 @@ export default class HttpGateway { } const result = await axios.get(url, config); - this.cache.set(url, result); + this.cache = this.cache.set(url, result); return result; } diff --git a/src/gateway/test/Cache.spec.ts b/src/gateway/test/Cache.spec.ts index ba65faf5..f793628b 100644 --- a/src/gateway/test/Cache.spec.ts +++ b/src/gateway/test/Cache.spec.ts @@ -2,26 +2,19 @@ import Cache from '../Cache'; describe('Cache', () => { it('can set and get a value', () => { - const cache = new Cache(); - cache.set('foo', 'baz'); - expect(cache.get('foo')).toBe('baz'); + expect(new Cache().set('foo', 'baz').get('foo')).toBe('baz'); }); it('in get(), throws an error if a key does not exist', () => { expect(() => new Cache().get('foo')).toThrow('The key foo does not exist'); - expect(() => { - const cache = new Cache(); - cache.set('foo', 'baz', 0, new Date().getTime() - 1); - cache.get('foo'); - }).toThrow('The key foo does not exist'); + expect(() => + new Cache().set('foo', 'baz', 0, new Date().getTime() - 1).get('foo') + ).toThrow('The key foo does not exist'); }); it('gets whether it has a value', () => { - const cache = new Cache(); - expect(cache.has('foo')).toBe(false); - - cache.set('foo', 'baz'); - expect(cache.has('foo')).toBe(true); + expect(new Cache().has('foo')).toBe(false); + expect(new Cache().set('foo', 'baz').has('foo')).toBe(true); }); describe('cache respects key expiration', () => { @@ -41,9 +34,9 @@ describe('Cache', () => { h: { val: 'lorem', exp: 0 }, i: { val: 'lorem', exp: 0 }, j: { val: 'lorem', exp: 0 }, - }); - cache.set('foo', 'ipsum'); - cache.set('baz', 'another'); + }) + .set('foo', 'ipsum') + .set('baz', 'another'); expect(cache.has('foo')).toBe(true); expect(cache.has('baz')).toBe(true);