|
| 1 | +import { |
| 2 | + set, |
| 3 | + keys, |
| 4 | + getMany, |
| 5 | + setMany, |
| 6 | + get, |
| 7 | + clear, |
| 8 | + del, |
| 9 | + delMany, |
| 10 | + createStore, |
| 11 | + promisifyRequest, |
| 12 | +} from 'idb-keyval'; |
| 13 | +import _ from 'underscore'; |
| 14 | +import fastMerge from '../../fastMerge'; |
| 15 | + |
| 16 | +// Same config as localforage, so we can swap the providers easily |
| 17 | +const customStore = createStore('OnyxDB', 'keyvaluepairs'); |
| 18 | + |
| 19 | +const provider = { |
| 20 | + getAllKeys: () => keys(customStore), |
| 21 | + |
| 22 | + multiGet: keysParam => getMany(keysParam, customStore) |
| 23 | + .then(values => _.map(values, (value, index) => [keysParam[index], value])), |
| 24 | + |
| 25 | + getItem: key => get(key, customStore), |
| 26 | + |
| 27 | + multiSet: pairs => setMany(pairs, customStore), |
| 28 | + |
| 29 | + setItem: (key, value) => set(key, value, customStore), |
| 30 | + |
| 31 | + multiMerge: pairs => customStore('readwrite', (store) => { |
| 32 | + const getValues = Promise.all(_.map(pairs, ([key]) => promisifyRequest(store.get(key)))); |
| 33 | + |
| 34 | + return getValues.then((values) => { |
| 35 | + const upsertMany = _.map(pairs, ([key, value], index) => { |
| 36 | + const prev = values[index]; |
| 37 | + const newValue = _.isObject(prev) ? fastMerge(prev, value) : value; |
| 38 | + return promisifyRequest(store.put(newValue, key)); |
| 39 | + }); |
| 40 | + return Promise.all(upsertMany); |
| 41 | + }); |
| 42 | + }), |
| 43 | + |
| 44 | + mergeItem(key, _changes, modifiedData) { |
| 45 | + return provider.multiMerge([[key, modifiedData]]); |
| 46 | + }, |
| 47 | + |
| 48 | + clear: () => clear(customStore), |
| 49 | + |
| 50 | + removeItem: key => del(key, customStore), |
| 51 | + |
| 52 | + removeItems: keysParam => delMany(keysParam, customStore), |
| 53 | +}; |
| 54 | + |
| 55 | +export default provider; |
0 commit comments