Skip to content

Commit

Permalink
Prevent cache.get when key is undefined (#882)
Browse files Browse the repository at this point in the history
  • Loading branch information
stevehobbsdev authored Mar 4, 2022
1 parent 451956f commit 70d53e7
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
22 changes: 22 additions & 0 deletions __tests__/cache/cache-manager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,28 @@ cacheFactories.forEach(cacheFactory => {
expect(await manager.get(key)).toStrictEqual(data);
});

it('should not fetch from the cache if allKeys returns empty array of keys', async () => {
// Simulate a cache implementation that returns an empty array for 'allKeys'
// but also has a valid entry in there - this tries to test a custom cache implementation
// that doesn't return an expected value for `allKeys`, it should just behave
// as any other entry that returns not found.
const cache = new InMemoryCache().enclosedCache;
const getSpy = jest.spyOn(cache, 'get');
const manager = new CacheManager(cache);

jest.spyOn(cache, 'allKeys').mockReturnValue([]);
cache.set(defaultKey.toKey(), defaultData);

expect(
await manager.get(
new CacheKey({ client_id: 'test', audience: 'test', scope: 'test' })
)
).not.toBeDefined();

// Make sure we don't try and get a cache value with a key of `undefined`
expect(getSpy).not.toHaveBeenCalledWith(undefined);
});

if (keyManifest) {
it('should update the key manifest when the key has only been added to the underlying cache', async () => {
const manifestKey = `${CACHE_KEY_PREFIX}::${defaultData.client_id}`;
Expand Down
5 changes: 4 additions & 1 deletion src/cache/cache-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,10 @@ export class CacheManager {
if (!keys) return;

const matchedKey = this.matchExistingCacheKey(cacheKey, keys);
wrappedEntry = await this.cache.get<WrappedCacheEntry>(matchedKey);

if (matchedKey) {
wrappedEntry = await this.cache.get<WrappedCacheEntry>(matchedKey);
}
}

// If we still don't have an entry, exit.
Expand Down

0 comments on commit 70d53e7

Please sign in to comment.