import { merge } from 'merge-anything' ; import { PluginWriteAction , PluginWriteActionPayload } from '../../../../core/src' ; import { StorePluginModuleConfig , StorePluginOptions , MakeRestoreBackup } from '../CreatePlugin' ; import { throwIfEmulatedError } from '../../helpers' ; export function writeActionFactory ( data , storePluginOptions , actionName , makeBackup ? ) { return function ( { payload , collectionPath , docId , pluginModuleConfig , } ) : void { throwIfEmulatedError ( payload , storePluginOptions ) ; if ( ! docId ) throw new Error ( 'An non-existent action was triggered on a collection' ) ; const collectionMap = data [ collectionPath ] ; if ( makeBackup ) makeBackup ( collectionPath , docId ) ; 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 }` ) ; if ( actionName === 'merge' ) { Object . entries ( payload ) . forEach ( ( [ key , value ] ) => { docDataToMutate [ key ] = merge ( docDataToMutate [ key ] , value ) ; } ) ; } if ( actionName === 'assign' || actionName === 'replace' ) { Object . entries ( payload ) . forEach ( ( [ key , value ] ) => { docDataToMutate [ key ] = value ; } ) ; } } ; }