Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add 'cloneData' option to buildMemoryStorage #581

Merged
merged 18 commits into from
Jul 1, 2023
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 17 additions & 4 deletions src/storage/memory.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { buildStorage, canStale, isExpired } from './build';
import type { AxiosStorage, StorageValue } from './types';
import type { AxiosStorage, NotEmptyStorageValue, StorageValue } from './types';

/**
* Modern function to natively deep clone.
Expand Down Expand Up @@ -30,8 +30,10 @@ declare const structuredClone: (<T>(value: T) => T) | undefined;
* delete memoryStorage.data[id];
* ```
*
* @param {boolean} cloneData If the data returned by `find()` should be cloned to avoid
* mutating the original data outside the `set()` method.
* @param {boolean | 'double'} cloneData Use `true` if the data returned by `find()`
* should be cloned to avoid mutating the original data outside the `set()` method. Use
* `'double'` to also clone before saving value in storage using `set()`. Disabled is
* default
* @param {number | false} cleanupInterval The interval in milliseconds to run a
* setInterval job of cleaning old entries. If false, the job will not be created.
* Disabled is default
Expand All @@ -41,7 +43,7 @@ declare const structuredClone: (<T>(value: T) => T) | undefined;
* usage. Disabled is default
*/
export function buildMemoryStorage(
cloneData = false,
cloneData: boolean | 'double' = false,
cleanupInterval: number | false = false,
maxEntries: number | false = false
) {
Expand All @@ -67,6 +69,17 @@ export function buildMemoryStorage(
}
}

/* istanbul ignore if 'only available on super recent browsers' */
if (cloneData === 'double' && value !== undefined) {
bhallionOhbibi marked this conversation as resolved.
Show resolved Hide resolved
arthurfiorette marked this conversation as resolved.
Show resolved Hide resolved
// Clone the value before storing to prevent future mutations
// from affecting cached data.
if (typeof structuredClone === 'function') {
value = structuredClone(value);
} else {
value = JSON.parse(JSON.stringify(value)) as NotEmptyStorageValue;
}
}

storage.data[key] = value;
},

Expand Down
29 changes: 29 additions & 0 deletions test/storage/memory.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,35 @@ describe('tests memory storage', () => {
expect(result2.data?.data).toBe('data');
});

// Expects that a when value saved using storage.set() is has his inner properties updated,
// a request to storage.get() should return unmodified value.
//
// https://github.com/arthurfiorette/axios-cache-interceptor/issues/580
it('ensures set() also clones data when cloneData is double', async () => {
const storage = buildMemoryStorage('double');

const data = { ...EMPTY_RESPONSE, data: 'data' };
await storage.set('key', {
arthurfiorette marked this conversation as resolved.
Show resolved Hide resolved
state: 'cached',
createdAt: Date.now(),
ttl: 1000 * 60 * 5, // 5 Minutes
data: data
});

data.data = 'another data';

arthurfiorette marked this conversation as resolved.
Show resolved Hide resolved
expect(storage.data['key']).not.toBeNull();
expect(storage.data['key']!.state).toBe('cached');
arthurfiorette marked this conversation as resolved.
Show resolved Hide resolved
expect(storage.data['key']!.data).not.toBeNull();
arthurfiorette marked this conversation as resolved.
Show resolved Hide resolved
expect(storage.data['key']!.data!.data).toBe('data');
arthurfiorette marked this conversation as resolved.
Show resolved Hide resolved

const result = (await storage.get('key')) as CachedStorageValue;

expect(result).not.toBeNull();
expect(result.state).toBe('cached');
expect(result.data.data).toBe('data');
});

it('tests cleanup function', async () => {
const storage = buildMemoryStorage(false, 500);

Expand Down