diff --git a/src/storages/KeyBuilderCS.ts b/src/storages/KeyBuilderCS.ts index a59d7208..20372358 100644 --- a/src/storages/KeyBuilderCS.ts +++ b/src/storages/KeyBuilderCS.ts @@ -43,6 +43,10 @@ export class KeyBuilderCS extends KeyBuilder implements MySegmentsKeyBuilder { buildTillKey() { return `${this.prefix}.${this.matchingKey}.segments.till`; } + + buildLastClear() { + return `${this.prefix}.lastClear`; + } } export function myLargeSegmentsKeyBuilder(prefix: string, matchingKey: string): MySegmentsKeyBuilder { diff --git a/src/storages/inLocalStorage/validateCache.ts b/src/storages/inLocalStorage/validateCache.ts index d2da969a..7c1fa31d 100644 --- a/src/storages/inLocalStorage/validateCache.ts +++ b/src/storages/inLocalStorage/validateCache.ts @@ -39,6 +39,18 @@ function validateExpiration(options: SplitIO.InLocalStorageOptions, settings: IS } return true; } + + // Clear on init + if (options.clearOnInit) { + let value: string | number | null = localStorage.getItem(keys.buildLastClear()); + if (value !== null) { + value = parseInt(value, 10); + if (!isNaNNumber(value) && value < Date.now() - MILLIS_IN_A_DAY) { + log.info(LOG_PREFIX + 'Clear on init was set and cache was cleared more than a day ago. Cleaning up cache'); + return true; + } + } + } } /** @@ -52,8 +64,15 @@ export function validateCache(options: SplitIO.InLocalStorageOptions, settings: splits.clear(); segments.clear(); largeSegments.clear(); + + // Update last clear timestamp + try { + localStorage.setItem(keys.buildLastClear(), Date.now() + ''); + } catch (e) { + settings.log.error(LOG_PREFIX + e); + } } - // Check if the cache is ready + // Check if ready from cache return splits.getChangeNumber() > -1; }