@@ -4,62 +4,23 @@ export type StorageAdapter = {
44 removeItem ?( key : string ) : Promise < void > ;
55} ;
66
7- export type StorageAdapterType =
8- | "custom"
9- | "localStorage"
10- | "asyncStorage"
11- | "memory" ;
12-
13- export const createMemoryStorageAdapter = ( ) : StorageAdapter => {
14- let value : string | null = null ;
7+ export function getLocalStorageAdapter ( ) : StorageAdapter {
8+ if (
9+ typeof localStorage === "undefined" ||
10+ ! ( "setItem" in localStorage ) ||
11+ ! ( "removeItem" in localStorage )
12+ ) {
13+ throw new Error (
14+ "localStorage is not available. Provide a custom storage adapter." ,
15+ ) ;
16+ }
1517 return {
16- getItem : async ( ) => value ,
17- setItem : async ( _key , nextValue ) => {
18- value = nextValue ;
18+ getItem : async ( key ) => localStorage . getItem ( key ) ,
19+ setItem : async ( key , value ) => {
20+ localStorage . setItem ( key , value ) ;
1921 } ,
20- removeItem : async ( ) => {
21- value = null ;
22+ removeItem : async ( key ) => {
23+ localStorage . removeItem ( key ) ;
2224 } ,
2325 } ;
24- } ;
25-
26- function isLocalStorageUsable ( ) {
27- return (
28- typeof localStorage !== "undefined" &&
29- "setItem" in localStorage &&
30- "removeItem" in localStorage
31- ) ;
32- }
33-
34- export function resolveStorageAdapter ( storage ?: StorageAdapter ) : {
35- adapter : StorageAdapter ;
36- type : StorageAdapterType ;
37- } {
38- if ( storage ) return { adapter : storage , type : "custom" } ;
39- if ( isLocalStorageUsable ( ) ) {
40- return {
41- adapter : {
42- getItem : async ( key ) => localStorage . getItem ( key ) ,
43- setItem : async ( key , value ) => {
44- localStorage . setItem ( key , value ) ;
45- } ,
46- removeItem : async ( key ) => {
47- localStorage . removeItem ( key ) ;
48- } ,
49- } ,
50- type : "localStorage" ,
51- } ;
52- }
53- // React Native: try AsyncStorage if available.
54- try {
55- // eslint-disable-next-line @typescript-eslint/no-require-imports
56- const asyncStorage = require ( "@react-native-async-storage/async-storage" ) ;
57- const adapter = asyncStorage ?. default ?? asyncStorage ;
58- if ( adapter ?. getItem && adapter ?. setItem ) {
59- return { adapter : adapter as StorageAdapter , type : "asyncStorage" } ;
60- }
61- } catch {
62- // ignore - not running in React Native or AsyncStorage not installed
63- }
64- return { adapter : createMemoryStorageAdapter ( ) , type : "memory" } ;
6526}
0 commit comments