Skip to content

Instantly share code, notes, and snippets.

@airtonix
Created March 8, 2019 00:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save airtonix/97849105a6f1763749a3a6b70253da43 to your computer and use it in GitHub Desktop.
Save airtonix/97849105a6f1763749a3a6b70253da43 to your computer and use it in GitHub Desktop.
isomorphic-localstorage-proxy
import { createLocalStorage } from "localstorage-ponyfill";
export const isBrowser =
typeof window !== 'undefined' &&
typeof window.document !== 'undefined';
export const isNode =
typeof process !== 'undefined' &&
process.versions != null &&
process.versions.node != null;
const storage = new Proxy (createLocalStorage({
mode: isNode && 'memory' || (isBrowser && 'browser')
}), {
get (store, prop) {
return store.getItem(prop);
},
/**
* Set a keys value
* @param {storage} store
* @param {*} prop
* @param {*} value
*
* Return value
* The set method should return a boolean value. Return true to indicate that assignment succeeded. If the set method returns false, and the assignment happened in strict-mode code, a TypeError will be thrown.
*/
set (store, prop, value) {
store.setItem(prop, value);
return store.getItem(prop) === value;
},
deleteProperty (store, prop) {
store.removeItem(prop);
}
});
export default storage;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment