import { unionBy, remove, assign } from 'lodash'; import { HandlerSetter, DuplicateChildren } from 'interfaces'; import Operation from '../Operation'; import checkCondition from './checkCondition'; export default function getDuplicateChildrenHandlers( parentEntityType: string, propKey: string, propValue: DuplicateChildren ): {selfHandlerSetters: Array, childHandlerSetters: Array} { // ---------- selfHandler ---------- const selfHandlerSetter: HandlerSetter = { handlerHolder: 'SELF', onAdd: [{ updatingParentType: null, operationModifier: (parentOperation: Operation) => { parentOperation.modify({ [propKey]: [] }); } }], onUpdate: [], onDelete: [] }; // ---------- childHandler ---------- const { childEntityType, mapFunc, limit, conditions } = propValue; const updateChildrenOfParentOperations = ( childOperation: Operation, beforeParentOperations: Array, afterParentOperations: Array ) => { const newChildPartialItem = mapFunc(childOperation.after); const newChildItemSelector = childOperation.itemSelector; const isBeforeChildOnCondition = checkCondition(childOperation.before, conditions); if (isBeforeChildOnCondition) { beforeParentOperations.forEach((parentOperation) => { parentOperation.delItemFromProp(propKey, newChildItemSelector); }); } const isAfterChildOnCondition = checkCondition(childOperation.after, conditions); if (isAfterChildOnCondition) { afterParentOperations.forEach((parentOperation) => { parentOperation.setItemToProp(propKey, newChildPartialItem, newChildItemSelector, limit); }); } }; const childHandlerSetter: HandlerSetter = { handlerHolder: childEntityType, onAdd: [{ updatingParentType: parentEntityType, operationModifier: ( childOperation: Operation, beforeParentOperations: Array, afterParentOperations: Array ) => { updateChildrenOfParentOperations(childOperation, beforeParentOperations, afterParentOperations); } }], onUpdate: [{ updatingParentType: parentEntityType, operationModifier: ( childOperation: Operation, beforeParentOperations: Array, afterParentOperations: Array ) => { updateChildrenOfParentOperations(childOperation, beforeParentOperations, afterParentOperations); } }], onDelete: [{ updatingParentType: parentEntityType, operationModifier: ( childOperation: Operation, beforeParentOperations: Array, afterParentOperations: Array ) => { updateChildrenOfParentOperations(childOperation, beforeParentOperations, afterParentOperations); } }] }; return { selfHandlerSetters: [selfHandlerSetter], childHandlerSetters: [childHandlerSetter] }; }