pinia-plugin-state-persistence
Version:
Pinia plugin for universal state persistence across synchronous and asynchronous storage systems, supporting advanced features like path inclusion/exclusion and custom serialization.
76 lines (75 loc) • 2.61 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.getNestedValue = void 0;
exports.createLogger = createLogger;
exports.setNestedValue = setNestedValue;
exports.applyStateFilter = applyStateFilter;
exports.queueTask = queueTask;
exports.getObjectDiff = getObjectDiff;
exports.isPromise = isPromise;
function createLogger(debug) {
return {
info: (message, ...args) => {
if (debug) {
console.info(`[PersistPlugin] INFO: ${message}`, ...args);
}
},
warn: (message, ...args) => {
if (debug) {
console.warn(`[PersistPlugin] WARN: ${message}`, ...args);
}
},
error: (message, ...args) => {
if (debug) {
console.error(`[PersistPlugin] ERROR: ${message}`, ...args);
}
},
};
}
// Get nested value from object using dot notation
const getNestedValue = (obj, path) => path.split('.').reduce((acc, key) => acc?.[key], obj);
exports.getNestedValue = getNestedValue;
// Set nested value in object using dot notation
function setNestedValue(obj, path, value) {
path.split('.').reduce((acc, key, idx, arr) => {
if (idx === arr.length - 1)
acc[key] = value;
else
acc[key] = acc[key] || {};
return acc[key];
}, obj);
}
function applyStateFilter(state, include, exclude) {
const includeArray = include ? [].concat(include) : null;
const excludeArray = exclude ? [].concat(exclude) : null;
const result = includeArray
? includeArray.reduce((acc, path) => {
const value = (0, exports.getNestedValue)(state, path);
if (value !== undefined)
setNestedValue(acc, path, value);
return acc;
}, {})
: { ...state };
excludeArray?.forEach((path) => {
const keys = path.split('.');
const parent = keys
.slice(0, -1)
.reduce((acc, key) => acc?.[key], result);
if (parent)
delete parent[keys.at(-1)];
});
return result;
}
// Queue processing for async storage
function queueTask(queues, key, task) {
if (!queues[key])
queues[key] = Promise.resolve();
queues[key] = queues[key].then(task).catch(error => console.error(`Error processing queue for key '${key}':`, error));
return queues[key];
}
function getObjectDiff(object1, object2) {
return Object.fromEntries(Object.entries(object1).filter(([key]) => !(key in object2)));
}
function isPromise(value) {
return value instanceof Promise;
}