@magnetarjs/plugin-vue3
Version:
Magnetar plugin vue3
32 lines (31 loc) • 1.49 kB
JavaScript
import { objGetOrSet } from 'getorset-anything';
import { isArray } from 'is-what';
import { getProp } from 'path-to-prop';
export function deletePropActionFactory(data, vue3StoreOptions, makeBackup) {
return function ({ payload, collectionPath, docId, pluginModuleConfig, }) {
// `deleteProp` action cannot be executed on collections
if (!docId)
throw new Error('An non-existent action was triggered on a collection');
const collectionMap = objGetOrSet(data, collectionPath, () => new Map());
const docData = collectionMap.get(docId);
if (!docData)
throw new Error(`Document data not found for id: ${collectionPath} ${docId}`);
if (makeBackup)
makeBackup(collectionPath, docId);
const payloadArray = isArray(payload) ? payload : [payload];
for (const propToDelete of payloadArray) {
const isNestedPropPath = /[./]/.test(propToDelete);
if (isNestedPropPath) {
const parts = propToDelete.split(/[./]/);
const lastPart = parts.pop();
const parentRef = getProp(docData, parts.join('.'));
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete parentRef[lastPart || ''];
}
else {
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete docData[propToDelete];
}
}
};
}