UNPKG

pinia-persist

Version:

Persist and rehydrate your Pinia state between page reloads

89 lines (65 loc) 3.06 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function t(t,r,e){return void 0===(t=(r.split?r.split("."):r).reduce(function(t,r){return t&&t[r]},t))?e:t}function r(t,r,e,n){return !/^(__proto__|constructor|prototype)$/.test(r)&&((r=r.split?r.split("."):r.slice(0)).slice(0,-1).reduce(function(t,r){return t[r]=t[r]||{}},t)[r.pop()]=e),t} function getOption(pluginOptions, options, key, fallback) { var _a, _b; return (_b = (_a = options[key]) !== null && _a !== void 0 ? _a : pluginOptions[key]) !== null && _b !== void 0 ? _b : fallback; } var createPersistPlugin = function createPersistPlugin(options) { var _a, _b; var defaultStorage = window && window.localStorage; var defaultAssertStorage = function defaultAssertStorage(storage) { var uniqueKey = '@@'; storage.setItem(uniqueKey, '1'); storage.removeItem(uniqueKey); }; var pluginOptions = options !== null && options !== void 0 ? options : {}; { ((_a = pluginOptions.assertStorage) !== null && _a !== void 0 ? _a : defaultAssertStorage)((_b = pluginOptions.storage) !== null && _b !== void 0 ? _b : defaultStorage); } function persistPlugin(context) { var _a, _b, _c, _d; // normalize var options = (_b = (_a = context.options) === null || _a === void 0 ? void 0 : _a.persist) !== null && _b !== void 0 ? _b : {}; var key = (_c = options.key) !== null && _c !== void 0 ? _c : context.store.$id; var overwrite = getOption(pluginOptions, options, 'overwrite', false); var storage = getOption(pluginOptions, options, 'storage', defaultStorage); var filter = getOption(pluginOptions, options, 'filter', function () { return true; }); var serialization = getOption(pluginOptions, options, 'serialization', JSON.stringify); var deserialization = getOption(pluginOptions, options, 'deserialization', JSON.parse); { ((_d = options.assertStorage) !== null && _d !== void 0 ? _d : defaultAssertStorage)(storage); } // hydrate try { var value = storage.getItem(key); if (value !== null) { var state = deserialization(value); if (overwrite) { context.store.$state = state; } else { context.store.$patch(state); } } } catch (error) { console.warn(error); } // persist context.store.$subscribe(function (mutation, state) { if (filter(mutation, state) === false) return; if (Array.isArray(options.includePaths)) { state = options.includePaths.reduce(function (partialState, path) { return r(partialState, path, t(state, path)); }, {}); } else if (Array.isArray(options.excludePaths)) { state = deserialization(serialization(state)); options.excludePaths.forEach(function (path) { return r(state, path, undefined); }, {}); } var value = serialization(state); storage.setItem(key, value); }); } return persistPlugin; }; exports.createPersistPlugin = createPersistPlugin;