UNPKG

@magnetarjs/plugin-vue3

Version:
48 lines (47 loc) 2.16 kB
import { isEqual } from '@magnetarjs/utils'; import { objGetOrSet } from 'getorset-anything'; import { isPlainObject } from 'is-what'; import { merge } from 'merge-anything'; export function writeActionFactory(data, vue3StoreOptions, actionName, makeBackup) { const write = ({ payload, collectionPath, docId, pluginModuleConfig }) => { // write actions 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()); if (makeBackup) makeBackup(collectionPath, docId); // always start from an empty document on 'replace' or when the doc is non existent if (actionName === 'replace' || !collectionMap.get(docId)) collectionMap.set(docId, {}); const docDataToMutate = collectionMap.get(docId); if (!docDataToMutate) throw new Error(`Document data not found for id: ${collectionPath} ${docId}`); const diffApplied = {}; if (actionName === 'merge') { for (const [key, value] of Object.entries(payload)) { const originalValue = docDataToMutate[key]; if (isEqual(originalValue, value)) continue; if (isPlainObject(originalValue) && isPlainObject(value)) { const newVal = merge(originalValue, value); diffApplied[key] = newVal; docDataToMutate[key] = newVal; } else { diffApplied[key] = value; docDataToMutate[key] = value; } } } if (actionName === 'assign' || actionName === 'replace') { for (const [key, value] of Object.entries(payload)) { if (isEqual(docDataToMutate[key], value)) continue; diffApplied[key] = value; docDataToMutate[key] = value; } } return { id: docId, current: docDataToMutate, diffApplied }; }; return write; }