pinia-plugin-store
Version:
pinia plugin store
60 lines (57 loc) • 1.88 kB
JavaScript
;
function getState(value) {
if (value) {
try {
return JSON.parse(value);
} catch (error) {
console.warn(error, 'unknown json format!');
}
}
}
function createStore(store, options) {
const { storage, encrypt, decrypt } = options;
const session = storage.getItem(store.$id);
if (session) {
const state = getState(decrypt ? decrypt(session) : session);
if (state) store.$state = state;
} else {
const json = JSON.stringify(store.$state);
storage.setItem(store.$id, encrypt ? encrypt(json) : json);
}
const subscription = (_mutation, state) => {
const json = JSON.stringify(state);
storage.setItem(store.$id, encrypt ? encrypt(json) : json);
};
store.$subscribe(subscription, { detached: true, deep: true, immediate: true });
}
function storePlugin(options) {
return (context) => {
const getOptions = { ...options };
const { store } = context;
const { stores, encrypt, decrypt } = getOptions;
if (stores && stores.length > 0) {
stores.forEach((storeKey) => {
if (typeof storeKey === 'string') {
if (storeKey === store.$id) {
const storage = getOptions.storage ?? localStorage;
createStore(store, { stores, storage, encrypt, decrypt });
}
} else if (storeKey.name === store.$id) {
const { storage, ciphertext } = storeKey;
const getStorage = () => {
if (storage) return storage;
if (getOptions.storage) return getOptions.storage;
return localStorage;
};
createStore(store, {
stores,
storage: getStorage(),
encrypt: ciphertext === false ? undefined : encrypt,
decrypt: ciphertext === false ? undefined : decrypt,
});
}
});
}
};
}
exports.storePlugin = storePlugin;