Skip to content

Commit

Permalink
Add tests for the api cache and refactor
Browse files Browse the repository at this point in the history
Signed-off-by: Axel Boberg <[email protected]>
  • Loading branch information
axelboberg committed Mar 24, 2024
1 parent cc1f3d0 commit 7eb8f29
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 14 deletions.
38 changes: 24 additions & 14 deletions api/classes/Cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,29 @@ class Cache {
this.#index.delete(firstKey)
}

/**
* Get a cached value
* by its key
* @param { String } key
* @returns { Promise.<any> }
*/
get (key) {
const entry = this.#index.get(key)

/*
If there is a pending promise for the value,
return that rather than starting a new request
*/
if (
entry &&
entry.status === 'pending' &&
entry.promise
) {
return entry.promise
}
return Promise.resolve(this.#index.get(key)?.value)
}

/**
* Cache the response of a provider function,
* the response will be returned if there's
Expand Down Expand Up @@ -72,20 +95,7 @@ class Cache {
}

if (this.#index.has(key)) {
const entry = this.#index.get(key)

/*
If there is a pending promise for the value,
return that rather than starting a new request
*/
if (
entry &&
entry.status === 'pending' &&
entry.promise
) {
return entry.promise
}
return this.#index.get(key)?.value
return this.get(key)
}

/*
Expand Down
21 changes: 21 additions & 0 deletions api/classes/Cache.unit.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// SPDX-FileCopyrightText: 2022 Sveriges Television AB
//
// SPDX-License-Identifier: MIT

const Cache = require('./Cache')
const cache = new Cache(5)

test('cache a provider', () => {
cache.cache('myKey', () => 10)
expect(cache.get('myKey')).resolves.toBe(10)
})

test('respect the max entry count', () => {
cache.cache('myKey1', () => 10)
cache.cache('myKey2', () => 10)
cache.cache('myKey3', () => 10)
cache.cache('myKey4', () => 10)
cache.cache('myKey5', () => 10)
cache.cache('myKey6', () => 10)
expect(cache.get('myKey1')).resolves.toBe(undefined)
})

0 comments on commit 7eb8f29

Please sign in to comment.