-
-
Save avorona/45f5ee158706d0c30a7dfdc70fab02e6 to your computer and use it in GitHub Desktop.
Simple sessionStorage/localStorage wrapper factory
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import storageFactory from "./storageFactory"; | |
export const localStore = storageFactory(localStorage); | |
export const sessionStore = storageFactory(sessionStorage); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* ISC License (ISC). Copyright 2017 Michal Zalecki */ | |
export function storageFactory(storage: Storage): Storage { | |
let inMemoryStorage: { [key: string]: string } = {}; | |
const length = 0; | |
function isSupported() { | |
try { | |
const testKey = "__some_random_key_you_are_not_going_to_use__"; | |
storage.setItem(testKey, testKey); | |
storage.removeItem(testKey); | |
return true; | |
} catch (e) { | |
return false; | |
} | |
} | |
function clear(): void { | |
if (isSupported()) { | |
storage.clear(); | |
} else { | |
inMemoryStorage = {}; | |
} | |
} | |
function getItem(name: string): string | null { | |
if (isSupported()) { | |
return storage.getItem(name); | |
} | |
if (inMemoryStorage.hasOwnProperty(name)) { | |
return inMemoryStorage[name]; | |
} | |
return null; | |
} | |
function key(index: number): string | null { | |
if (isSupported()) { | |
return storage.key(index); | |
} else { | |
return Object.keys(inMemoryStorage)[index] || null; | |
} | |
} | |
function removeItem(name: string): void { | |
if (isSupported()) { | |
storage.removeItem(name); | |
} else { | |
delete inMemoryStorage[name]; | |
} | |
} | |
function setItem(name: string, value: string): void { | |
if (isSupported()) { | |
storage.setItem(name, value); | |
} else { | |
inMemoryStorage[name] = String(value); // not everyone uses TypeScript | |
} | |
} | |
return { | |
getItem, | |
setItem, | |
removeItem, | |
clear, | |
key, | |
length, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment