-
-
Notifications
You must be signed in to change notification settings - Fork 17
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- just the source code itself
- Loading branch information
0 parents
commit 4223a23
Showing
2 changed files
with
66 additions
and
0 deletions.
There are no files selected for viewing
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
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) | ||
} | ||
} |
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
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 | ||
}, {}) | ||
} |