From 3f589f67a7033531e4b91b953b2ead5baeab35b6 Mon Sep 17 00:00:00 2001 From: Alex Klarfeld Date: Wed, 24 Apr 2024 18:41:28 -0700 Subject: [PATCH] Added error handling if flush occurs before initialization --- src/constants.ts | 2 +- src/index.ts | 11 ++++++++--- test/e2e/core.e2e.test.ts | 8 ++++++++ 3 files changed, 17 insertions(+), 4 deletions(-) diff --git a/src/constants.ts b/src/constants.ts index 1055d35..526e3dd 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -39,7 +39,7 @@ const errors = { NO_CLIENT_ID: 'No Client ID Provided, set SUPERGOOD_CLIENT_ID or pass it as an argument', NO_CLIENT_SECRET: - 'No Client Secret Provided, set SUPERGOOD_CLIENT_SECRET or pass it as an argument' + 'No Client Secret Provided, set SUPERGOOD_CLIENT_SECRET or pass it as an argument', }; const SensitiveKeyActions = { diff --git a/src/index.ts b/src/index.ts index 61d7f9a..ad7ccbe 100644 --- a/src/index.ts +++ b/src/index.ts @@ -297,6 +297,11 @@ const Supergood = () => { // Force flush cache means don't wait for responses const flushCache = async ({ force } = { force: false }) => { + + if(!responseCache || !requestCache) { + return; + } + const responseCacheKeys = responseCache.keys(); const requestCacheKeys = requestCache.keys(); const responseCacheValues = Object.values(responseCache.mget(responseCacheKeys)); @@ -403,11 +408,11 @@ const Supergood = () => { clearInterval(remoteConfigFetchInterval); // If there are hanging requests, wait a second - if (requestCache.keys().length > 0) { + if (requestCache?.keys().length > 0) { await sleep(supergoodConfig.waitAfterClose); } - interceptor.teardown(); + interceptor?.teardown(); await flushCache({ force }); return false; }; @@ -416,7 +421,7 @@ const Supergood = () => { // If the request cache isn't empty, this means that // there are responses that are still being processed. // Wait for them to finish before flushing the cache. - if (requestCache.keys().length > 0) { + if (requestCache?.keys().length > 0) { await sleep(supergoodConfig.waitAfterClose); } diff --git a/test/e2e/core.e2e.test.ts b/test/e2e/core.e2e.test.ts index b891a96..1703b57 100644 --- a/test/e2e/core.e2e.test.ts +++ b/test/e2e/core.e2e.test.ts @@ -401,4 +401,12 @@ describe('core functionality', () => { expect(postEventsMock).not.toHaveBeenCalled(); }); }); + + describe('clean error handling', () => { + it('should not crash if a flush is called before an init', async () => { + await Supergood.close(); + await Supergood.waitAndFlushCache(); + expect(postEventsMock).not.toHaveBeenCalled(); + }); + }); });