UNPKG

@idealyst/storage

Version:

Cross-platform storage abstraction for React and React Native

84 lines (73 loc) 2 kB
import { IStorage } from './types'; class WebStorage implements IStorage { private storage: Storage; constructor(storage: Storage = window.localStorage) { this.storage = storage; } async getItem(key: string): Promise<string | null> { try { return this.storage.getItem(key); } catch (error) { console.error('Error getting item from storage:', error); return null; } } async setItem(key: string, value: string): Promise<void> { try { this.storage.setItem(key, value); } catch (error) { console.error('Error setting item in storage:', error); throw error; } } async removeItem(key: string): Promise<void> { try { this.storage.removeItem(key); } catch (error) { console.error('Error removing item from storage:', error); throw error; } } async clear(): Promise<void> { try { this.storage.clear(); } catch (error) { console.error('Error clearing storage:', error); throw error; } } async getAllKeys(): Promise<string[]> { try { const keys: string[] = []; for (let i = 0; i < this.storage.length; i++) { const key = this.storage.key(i); if (key !== null) { keys.push(key); } } return keys; } catch (error) { console.error('Error getting all keys from storage:', error); return []; } } async multiGet(keys: string[]): Promise<Array<[string, string | null]>> { return Promise.all( keys.map(async (key) => { const value = await this.getItem(key); return [key, value] as [string, string | null]; }) ); } async multiSet(keyValuePairs: Array<[string, string]>): Promise<void> { for (const [key, value] of keyValuePairs) { await this.setItem(key, value); } } async multiRemove(keys: string[]): Promise<void> { for (const key of keys) { await this.removeItem(key); } } } export default WebStorage;