Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
28 changes: 23 additions & 5 deletions __mocks__/@react-native-async-storage/async-storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export default class AsyncStorage {
callback?.(undefined, value);
return Promise.resolve(value);
}

static setItem(
key: string,
value: string,
Expand All @@ -35,7 +35,7 @@ export default class AsyncStorage {
callback?.(undefined);
return Promise.resolve();
}

static removeItem(
key: string,
callback?: (error?: Error, result?: string | null) => void
Expand All @@ -47,10 +47,28 @@ export default class AsyncStorage {
callback?.(undefined, value);
return Promise.resolve(value);
}

static clearStore(): Promise<void> {

static getAllKeys(): Promise<string[]> {
return Promise.resolve(Object.keys(AsyncStorage.items));
}

static clear(): Promise<void> {
AsyncStorage.items = {};
return Promise.resolve();
}


static multiGet(keys: readonly string[]): Promise<[string, string | null][]> {
return Promise.resolve(
keys.map((key) => [key, AsyncStorage.items[key] ?? null] as [string, string | null])
);
}

static getMany(keys: readonly string[]): Promise<Record<string, string | null>> {
const record: Record<string, string | null> = {};
for (const key of keys) {
record[key] = AsyncStorage.items[key] ?? null;
}
return Promise.resolve(record);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,7 @@ describe('createBatchEventProcessor', () => {
expect(() => createBatchEventProcessor({ eventStore })).not.toThrow();

isAsyncStorageAvailable = true;
MockAsyncStorageCache.mockReset();
});

it('wraps the provided eventStore in a SyncPrefixStore if a SyncCache is provided as eventStore', () => {
Expand Down
22 changes: 20 additions & 2 deletions lib/utils/cache/async_storage_cache.react_native.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

import { vi, describe, it, expect } from 'vitest';
import { AsyncStorageCache } from './async_storage_cache.react_native';
import { AsyncStoreWithBatchedGet } from './store';
import { getDefaultAsyncStorage } from '../import.react_native/@react-native-async-storage/async-storage';

vi.mock('@react-native-async-storage/async-storage');
Expand Down Expand Up @@ -71,11 +72,28 @@ describe('AsyncStorageCache', () => {
expect(await cache.getKeys()).toEqual(['key1', 'key2']);
});

it('should return an array of values for an array of keys when getBatched is called', async () => {
it('should be an AsyncStoreWithBatchedGet', () => {
expect(new AsyncStorageCache()).toBeInstanceOf(AsyncStoreWithBatchedGet);
});

it('should return an array of values for an array of keys using a single multiGet call when getBatched is called', async () => {
const cache = new AsyncStorageCache();
await cache.set('key1', 'value1');
await cache.set('key2', 'value2');

expect(await cache.getBatched(['key1', 'key2'])).toEqual(['value1', 'value2']);
const multiGetSpy = vi.spyOn(asyncStorage, 'multiGet');

expect(await cache.getBatched(['key2', 'key1'])).toEqual(['value2', 'value1']);
expect(multiGetSpy).toHaveBeenCalledOnce();
expect(multiGetSpy).toHaveBeenCalledWith(['key2', 'key1']);

multiGetSpy.mockRestore();
});

it('should return undefined for missing keys when getBatched is called', async () => {
const cache = new AsyncStorageCache();
await cache.set('key1', 'value1');

expect(await cache.getBatched(['key1', 'missing'])).toEqual(['value1', undefined]);
});
});
6 changes: 3 additions & 3 deletions lib/utils/cache/async_storage_cache.react_native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,11 @@
*/

import { Maybe } from "../type";
import { AsyncStore } from "./store";
import { AsyncStore, AsyncStoreWithBatchedGet } from "./store";
import { getDefaultAsyncStorage } from "../import.react_native/@react-native-async-storage/async-storage";
import { Platform } from '../../platform_support';

export class AsyncStorageCache implements AsyncStore<string> {
export class AsyncStorageCache extends AsyncStoreWithBatchedGet<string> implements AsyncStore<string> {
public readonly operation = 'async';
private asyncStorage = getDefaultAsyncStorage();

Expand All @@ -46,7 +46,7 @@ export class AsyncStorageCache implements AsyncStore<string> {

async getBatched(keys: string[]): Promise<Maybe<string>[]> {
const items = await this.asyncStorage.multiGet(keys);
return items.map(([key, value]) => value ?? undefined);
return items.map(([, value]) => value ?? undefined);
}
}

Expand Down
80 changes: 78 additions & 2 deletions lib/utils/cache/store.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,16 @@
* limitations under the License.
*/

import { describe, it, expect } from 'vitest';
import { SyncPrefixStore, AsyncPrefixStore } from './store';
import { describe, it, expect, vi } from 'vitest';
import {
SyncPrefixStore,
AsyncPrefixStore,
SyncStoreWithBatchedGet,
AsyncStoreWithBatchedGet,
getBatchedSync,
getBatchedAsync,
} from './store';
import { Maybe } from '../type';
import { getMockSyncCache, getMockAsyncCache } from '../../tests/mock/mock_cache';

describe('SyncPrefixStore', () => {
Expand Down Expand Up @@ -288,4 +296,72 @@ describe('AsyncPrefixStore', () => {
expect(values).toEqual(expect.arrayContaining(['value1', 'value2']));
});
});
});

class BatchedSyncStore extends SyncStoreWithBatchedGet<string> {
private data = new Map<string, string>();
set(key: string, value: string): void { this.data.set(key, value); }
get(key: string): Maybe<string> { return this.data.get(key); }
remove(key: string): void { this.data.delete(key); }
getKeys(): string[] { return [...this.data.keys()]; }
getBatched(keys: string[]): Maybe<string>[] { return keys.map((key) => this.data.get(key)); }
}

class BatchedAsyncStore extends AsyncStoreWithBatchedGet<string> {
private data = new Map<string, string>();
async set(key: string, value: string): Promise<void> { this.data.set(key, value); }
async get(key: string): Promise<Maybe<string>> { return this.data.get(key); }
async remove(key: string): Promise<void> { this.data.delete(key); }
async getKeys(): Promise<string[]> { return [...this.data.keys()]; }
async getBatched(keys: string[]): Promise<Maybe<string>[]> { return keys.map((key) => this.data.get(key)); }
}

describe('getBatchedSync', () => {
it('should use getBatched of a SyncStoreWithBatchedGet', () => {
const store = new BatchedSyncStore();
store.set('key1', 'value1');
store.set('key2', 'value2');
const getBatchedSpy = vi.spyOn(store, 'getBatched');
const getSpy = vi.spyOn(store, 'get');

expect(getBatchedSync(store, ['key2', 'missing', 'key1'])).toEqual(['value2', undefined, 'value1']);
expect(getBatchedSpy).toHaveBeenCalledOnce();
expect(getBatchedSpy).toHaveBeenCalledWith(['key2', 'missing', 'key1']);
expect(getSpy).not.toHaveBeenCalled();
});

it('should fall back to get for each key if the store is not a SyncStoreWithBatchedGet', () => {
const store = getMockSyncCache<string>();
store.set('key1', 'value1');
store.set('key2', 'value2');
const getSpy = vi.spyOn(store, 'get');

expect(getBatchedSync(store, ['key2', 'missing', 'key1'])).toEqual(['value2', undefined, 'value1']);
expect(getSpy).toHaveBeenCalledTimes(3);
});
});

describe('getBatchedAsync', () => {
it('should use getBatched of an AsyncStoreWithBatchedGet', async () => {
const store = new BatchedAsyncStore();
await store.set('key1', 'value1');
await store.set('key2', 'value2');
const getBatchedSpy = vi.spyOn(store, 'getBatched');
const getSpy = vi.spyOn(store, 'get');

expect(await getBatchedAsync(store, ['key2', 'missing', 'key1'])).toEqual(['value2', undefined, 'value1']);
expect(getBatchedSpy).toHaveBeenCalledOnce();
expect(getBatchedSpy).toHaveBeenCalledWith(['key2', 'missing', 'key1']);
expect(getSpy).not.toHaveBeenCalled();
});

it('should fall back to get for each key if the store is not an AsyncStoreWithBatchedGet', async () => {
const store = getMockAsyncCache<string>();
await store.set('key1', 'value1');
await store.set('key2', 'value2');
const getSpy = vi.spyOn(store, 'get');

expect(await getBatchedAsync(store, ['key2', 'missing', 'key1'])).toEqual(['value2', undefined, 'value1']);
expect(getSpy).toHaveBeenCalledTimes(3);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/**
* Copyright 2025, Optimizely
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { vi, describe, it, expect } from 'vitest';
import { ensureMultiGet } from './async-storage';

describe('ensureMultiGet', () => {
it('should preserve multiGet when already present (v1/v2)', () => {
const multiGet = vi.fn();
const storage = {
getItem: vi.fn(),
setItem: vi.fn(),
removeItem: vi.fn(),
getAllKeys: vi.fn(),
clear: vi.fn(),
multiGet,
};

const result = ensureMultiGet(storage);

expect(result.multiGet).toBe(multiGet);
});

it('should construct multiGet from getMany when multiGet is absent (v3)', async () => {
const items: Record<string, string> = { a: '1', b: '2' };
const storage = {
getItem: vi.fn(),
setItem: vi.fn(),
removeItem: vi.fn(),
getAllKeys: vi.fn(),
clear: vi.fn(),
getMany: vi.fn((keys: readonly string[]) => {
const record: Record<string, string | null> = {};
for (const key of keys) { record[key] = items[key] ?? null; }
return Promise.resolve(record);
}),
};

const result = ensureMultiGet(storage);

expect(result.multiGet).toBeDefined();

const pairs = await result.multiGet(['b', 'missing', 'a']);
expect(pairs).toEqual([
['b', '2'],
['missing', null],
['a', '1'],
]);
});

it('should return pairs in the requested key order regardless of getMany record order', async () => {
const items: Record<string, string> = { x: 'vx', y: 'vy', z: 'vz' };
const storage = {
getItem: vi.fn(),
setItem: vi.fn(),
removeItem: vi.fn(),
getAllKeys: vi.fn(),
clear: vi.fn(),
getMany: vi.fn((keys: readonly string[]) => {
const record: Record<string, string | null> = {};
const reversed = [...keys].reverse();
for (const key of reversed) { record[key] = items[key] ?? null; }
return Promise.resolve(record);
}),
};

const result = ensureMultiGet(storage);
const pairs = await result.multiGet(['z', 'x', 'y']);

expect(pairs).toEqual([
['z', 'vz'],
['x', 'vx'],
['y', 'vy'],
]);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,45 @@
* limitations under the License.
*/

import type { AsyncStorageStatic } from '@react-native-async-storage/async-storage'
import { Platform } from '../../../platform_support';

export interface AsyncStorageCompat {
getItem(key: string): Promise<string | null>;
setItem(key: string, value: string): Promise<void>;
removeItem(key: string): Promise<void>;
getAllKeys(): Promise<readonly string[]>;
clear(): Promise<void>;
multiGet(keys: readonly string[]): Promise<readonly [string, string | null][]>;
}

interface RawAsyncStorage {
getItem(key: string): Promise<string | null>;
setItem(key: string, value: string): Promise<void>;
removeItem(key: string): Promise<void>;
getAllKeys(): Promise<readonly string[]>;
clear(): Promise<void>;
multiGet?(keys: readonly string[]): Promise<readonly [string, string | null][]>;
getMany?(keys: readonly string[]): Promise<Record<string, string | null>>;
}

export const MODULE_NOT_FOUND_REACT_NATIVE_ASYNC_STORAGE = 'Module not found: @react-native-async-storage/async-storage';

export const getDefaultAsyncStorage = (): AsyncStorageStatic => {
export const ensureMultiGet = (storage: RawAsyncStorage): AsyncStorageCompat => {
if (!storage.multiGet && storage.getMany) {
const getMany = storage.getMany.bind(storage);
storage.multiGet = async (keys: readonly string[]): Promise<[string, string | null][]> => {
const record = await getMany(keys);
return keys.map((key: string) => [key, record[key] ?? null] as [string, string | null]);
};
}
return storage as AsyncStorageCompat;
};

export const getDefaultAsyncStorage = (): AsyncStorageCompat => {
try {
// eslint-disable-next-line @typescript-eslint/no-var-requires
return require('@react-native-async-storage/async-storage').default;
const storage = require('@react-native-async-storage/async-storage').default;
return ensureMultiGet(storage);
} catch (e) {
throw new Error(MODULE_NOT_FOUND_REACT_NATIVE_ASYNC_STORAGE);
}
Expand Down
10 changes: 5 additions & 5 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 5 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -147,11 +147,11 @@
"webpack": "^5.94.0"
},
"peerDependencies": {
"@react-native-async-storage/async-storage": ">=1.0.0 <3.0.0",
"@react-native-community/netinfo": ">=5.0.0 <12.0.0",
"fast-text-encoding": "^1.0.6",
"react-native-get-random-values": "^1.11.0",
"ua-parser-js": "^1.0.38"
"@react-native-async-storage/async-storage": ">=1.0.0 <4.0.0",
"@react-native-community/netinfo": ">=5.0.0 <13.0.0",
"fast-text-encoding": ">=1.0.6 <2.0.0",
"react-native-get-random-values": ">=1.11.0 <3.0.0",
"ua-parser-js": ">=1.0.38 <2.0.0"
},
"peerDependenciesMeta": {
"@react-native-async-storage/async-storage": {
Expand Down
Loading