Skip to content

Commit

Permalink
fix fetch from api after loading stale cache when skip api set
Browse files Browse the repository at this point in the history
  • Loading branch information
blackjid committed Sep 17, 2024
1 parent 2f4bbbb commit cba3282
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
10 changes: 8 additions & 2 deletions flagsmith-core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,7 @@ const Flagsmith = class {
try {
const json = JSON.parse(res);
let cachePopulated = false;
let staleCachePopulated = false;
if (json && json.api === this.api && json.environmentID === this.environmentID) {
let setState = true;
if (this.identity && (json.identity !== this.identity)) {
Expand All @@ -418,6 +419,7 @@ const Flagsmith = class {
}
else if (json.ts && this.cacheOptions.loadStale) {
this.log("Loading stale cache, timestamp ts:" + json.ts + " ttl: " + this.cacheOptions.ttl + " time elapsed since cache: " + (new Date().valueOf()-json.ts)+"ms")
staleCachePopulated = true;
setState = true;
}
}
Expand All @@ -439,13 +441,17 @@ const Flagsmith = class {
}

if (cachePopulated) { // retrieved flags from local storage
const shouldFetchFlags = !preventFetch && (!this.cacheOptions.skipAPI||!cachePopulated)
const shouldFetchFlags = !preventFetch && (
!this.cacheOptions.skipAPI ||
!cachePopulated ||
(cachePopulated && staleCachePopulated)
)
this._onChange(null,
{ isFromServer: false, flagsChanged, traitsChanged },
this._loadedState(null, FlagSource.CACHE, shouldFetchFlags)
);
this.oldFlags = this.flags;
if (this.cacheOptions.skipAPI && cachePopulated) {
if (this.cacheOptions.skipAPI && cachePopulated && !staleCachePopulated) {
this.log("Skipping API, using cache")
}
if (shouldFetchFlags) {
Expand Down
18 changes: 18 additions & 0 deletions test/cache.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,24 @@ describe('Cache', () => {
...defaultStateAlt,
});
});
test('should get flags from API when stale cache is loaded and skipAPI is set', async () => {
const onChange = jest.fn();
const { flagsmith, initConfig, AsyncStorage, mockFetch } = getFlagsmith({
cacheFlags: true,
onChange,
cacheOptions: { ttl: 1, skipAPI: true, loadStale: true },
});
await AsyncStorage.setItem('BULLET_TRAIN_DB', JSON.stringify({
...defaultStateAlt,
ts: new Date().valueOf() - 100,
}));
await flagsmith.init(initConfig);
expect(onChange).toHaveBeenCalledTimes(1);
expect(mockFetch).toHaveBeenCalledTimes(1);
expect(getStateToCheck(flagsmith.getState())).toEqual({
...defaultStateAlt,
});
});
test('should validate flags are unchanged when fetched', async () => {
const onChange = jest.fn();
const { flagsmith, initConfig, AsyncStorage, mockFetch } = getFlagsmith({
Expand Down

0 comments on commit cba3282

Please sign in to comment.