UNPKG

@fmal/cerebral-storage

Version:

Storage provider for Cerebral

51 lines (45 loc) 1.67 kB
import StorageProvider from './StorageProvider'; export { default as StorageProviderError } from './StorageProviderError'; export default (function (options) { if (options === void 0) { options = {}; } return function (_ref) { var _providers; var app = _ref.app, name = _ref.name; var _options = options, _options$target = _options.target, targetStorage = _options$target === void 0 ? localStorage : _options$target, _options$json = _options.json, json = _options$json === void 0 ? true : _options$json, sync = _options.sync, prefix = _options.prefix; var finalPrefix = prefix ? prefix + '.' : ''; app.once('initialized:model', function () { Object.keys(sync || {}).forEach(function (syncKey) { var value = targetStorage.getItem(finalPrefix + syncKey); if (!value) { return; } var path = sync[syncKey].split('.'); app.model.set(path, json ? JSON.parse(value) : value); }); }); if (sync) { app.on('flush', function (changes) { changes.forEach(function (change) { Object.keys(sync).forEach(function (syncKey) { if (change.path.join('.').indexOf(sync[syncKey]) === 0) { var value = app.getState(sync[syncKey]); value === undefined ? targetStorage.removeItem(finalPrefix + syncKey) : targetStorage.setItem(finalPrefix + syncKey, json ? JSON.stringify(value) : value); } }); }); }); } return { providers: (_providers = {}, _providers[name] = StorageProvider(options), _providers) }; }; });