|
| 1 | +import type { StorageService, Get } from "./types"; |
| 2 | + |
| 3 | +export const createStorageService = (prefix: string): StorageService => { |
| 4 | + const prefixKey = (key: string): string => `${prefix}:${key}`; |
| 5 | + |
| 6 | + const put = (key: string, value: unknown): void => { |
| 7 | + const valueToStore = typeof value === "string" ? value : JSON.stringify(value); |
| 8 | + |
| 9 | + try { |
| 10 | + localStorage.setItem(prefixKey(key), valueToStore); |
| 11 | + } catch (error) { |
| 12 | + if (error instanceof DOMException && error.name === "QuotaExceededError") { |
| 13 | + console.error("localStorage quota exceeded"); |
| 14 | + return; |
| 15 | + } |
| 16 | + console.error(error); |
| 17 | + } |
| 18 | + }; |
| 19 | + |
| 20 | + const get: Get = <T>(key: string, defaultValue?: T): T | undefined => { |
| 21 | + let storedValue: string | null; |
| 22 | + try { |
| 23 | + storedValue = localStorage.getItem(prefixKey(key)); |
| 24 | + } catch (error) { |
| 25 | + console.error(error); |
| 26 | + return defaultValue; |
| 27 | + } |
| 28 | + |
| 29 | + if (storedValue === null) return defaultValue; |
| 30 | + |
| 31 | + if (typeof defaultValue === "string") return storedValue as T; |
| 32 | + |
| 33 | + try { |
| 34 | + return JSON.parse(storedValue) as T; |
| 35 | + } catch { |
| 36 | + return storedValue as unknown as T; |
| 37 | + } |
| 38 | + }; |
| 39 | + |
| 40 | + const remove = (key: string): void => { |
| 41 | + try { |
| 42 | + localStorage.removeItem(prefixKey(key)); |
| 43 | + } catch (error) { |
| 44 | + console.error(error); |
| 45 | + } |
| 46 | + }; |
| 47 | + |
| 48 | + const clear = (): void => { |
| 49 | + const keysToRemove: string[] = []; |
| 50 | + for (let i = 0; i < localStorage.length; i++) { |
| 51 | + const key = localStorage.key(i); |
| 52 | + if (key?.startsWith(`${prefix}:`)) { |
| 53 | + keysToRemove.push(key); |
| 54 | + } |
| 55 | + } |
| 56 | + for (const key of keysToRemove) { |
| 57 | + try { |
| 58 | + localStorage.removeItem(key); |
| 59 | + } catch (error) { |
| 60 | + console.error(error); |
| 61 | + } |
| 62 | + } |
| 63 | + }; |
| 64 | + |
| 65 | + return { put, get, remove, clear }; |
| 66 | +}; |
0 commit comments