Created
October 7, 2016 21:40
-
-
Save franciscotln/534ac11d2dbb5971dae7678f9fb28e0f to your computer and use it in GitHub Desktop.
storageDriver for Cycle.js
This file contains 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 { ReplaySubject } from 'rxjs'; | |
function StorageWrapper(storage) { | |
function set(key, value) { | |
storage.setItem(key, JSON.stringify(value)); | |
return value; | |
} | |
function get(key) { | |
return JSON.parse(storage.getItem(key)) | |
} | |
function getAll() { | |
return Object.keys(storage).map(key => { | |
const item = {}; | |
item[key] = get(key); | |
return item; | |
}); | |
} | |
function remove(key) { | |
const item = get(key); | |
storage.removeItem(key); | |
return item[key]; | |
} | |
function clear() { | |
return storage.clear(); | |
} | |
const wrappedStorage = { set, get, getAll, remove, clear }; | |
Object.defineProperty(wrappedStorage, 'length', { get: () => storage.length }); | |
return wrappedStorage; | |
} | |
export function makeStorageDriver(storageType) { | |
let type; | |
if (typeof storageType === 'string') { | |
type = storageType.toLowerCase(); | |
} else { | |
console.error('Invalid argument. "makeStorageDriver" accepts a string as argument.'); | |
} | |
if (!['local', 'session'].includes(type)) { | |
console.error('Invalid argument. The argument for "makeStorageDriver" must be "local" or "session".'); | |
} | |
const storage = StorageWrapper(window[`${type}Storage`]); | |
const storageSource$ = new ReplaySubject(); | |
storageSource$.next(storage); | |
function storageDriver(storage$) { | |
storage$.switchMapTo(storageSource$).subscribe(storageSource$); | |
return storageSource$; | |
}; | |
return storageDriver; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment