Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple sessionStorage/localStorage wrapper factory
import storageFactory from "./storageFactory";
export const localStore = storageFactory(localStorage);
export const sessionStore = storageFactory(sessionStorage);
/* 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,
};
}
@ZaLiTHkA

This comment has been minimized.

Copy link

ZaLiTHkA commented May 21, 2018

just out of curiosity, wouldn't it be better to move the contents of isSupported out so it only runs once, rather than creating and then deleting __some_random_key_you_are_not_going_to_use__ at the start of every action?

for example:

function storageFactory(storage) {
  let inMemoryStorage = {}; 
  let browserStorageSupported;

  try {
    const key = "__some_random_key_you_are_not_going_to_use__";
    storage.setItem(key, key);
    storage.removeItem(key);
    browserStorageSupported = true;
  } catch (e) {
    browserStorageSupported = false;
  }

  function getItem(key) {
    if (browserStorageSupported) {
      return storage.getItem(key);
    }
    return inMemoryStorage[key] || null;
  }

  ...
}
@MichalZalecki

This comment has been minimized.

Copy link
Owner Author

MichalZalecki commented Sep 26, 2018

@MichalZalecki

This comment has been minimized.

Copy link
Owner Author

MichalZalecki commented Sep 26, 2018

@ZaLiTHkA Maybe, but I like function better than a "helper" variables.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.