Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
- just the source code itself
  • Loading branch information
agilgur5 committed May 19, 2019
0 parents commit 4223a23
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
23 changes: 23 additions & 0 deletions localStorageAdaptor.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
export function clear () {
return callWithPromise(window.localStorage.clear)
}

export function getItem (key) {
return callWithPromise(window.localStorage.getItem, key)
}

export function removeItem (key) {
return callWithPromise(window.localStorage.removeItem, key)
}

export function setItem (key, value) {
return callWithPromise(window.localStorage.setItem, key, value)
}

function callWithPromise (func, ...args) {
try {
return Promise.resolve(func(...args))
} catch (err) {
return Promise.reject(err)
}
}
43 changes: 43 additions & 0 deletions persist.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { onSnapshot, applySnapshot } from 'mobx-state-tree'

import * as LocalStorage from './localStorageAdaptor.js'

export const persist = (name, store, options = {}) => {
let {storage, whitelist, blacklist, jsonify} = options

if (typeof window.localStorage !== 'undefined' && window.localStorage === storage) {
storage = LocalStorage
}
const whitelistDict = arrToDict(whitelist)
const blacklistDict = arrToDict(blacklist)
if (!jsonify) { jsonify = true } // default to true like mobx-persist

onSnapshot(store, (_snapshot) => {
const snapshot = { ..._snapshot }
Object.keys(snapshot).forEach((key) => {
if (whitelist && !whitelistDict[key]) {
delete snapshot[key]
}
if (blacklist && blacklistDict[key]) {
delete snapshot[key]
}
})

const data = !jsonify ? snapshot : JSON.stringify(snapshot)
storage.setItem(name, data)
})

return storage.getItem(name)
.then((data) => {
const snapshot = !jsonify ? data : JSON.parse(data)
applySnapshot(store, snapshot)
})
}

function arrToDict (arr) {
if (!arr) { return {} }
return arr.reduce((dict, elem) => {
dict[elem] = true
return dict
}, {})
}

0 comments on commit 4223a23

Please sign in to comment.