import { toJS } from 'mobx' ; import { BaseUpdateDto } from 'common/models/dtos/updateDto' ; export interface IItemsCRUDController < T > { add ( ... items ) : Promise < void > ; duplicate ( id ) : Promise < void > ; delete ( id ) : Promise < void > ; update ( item ) : Promise < void > ; } export class ItemsCRUDController < T extends { id : string ; } > implements IItemsCRUDController < T > { constructor ( readonly types , readonly submit , readonly updateExisting ) { } public add ( ... items ) { return this . submit ( { add : items , } ) ; } async duplicate ( id ) { const p = this . types ( ) ?. find ( lp => lp . id === id ) ; if ( ! p ) { throw new Error ( 'Item to duplicate was not found' ) ; } return this . submit ( { add : [ toJS ( { ... p , id : null } ) ] , } ) ; } async delete ( id ) { const types = this . types ( ) ; const existingIndex = types ?. findIndex ( pp => pp . id === id ) ; if ( ! types || existingIndex < 0 ) { throw new Error ( 'Item to delete was not found, id = ' + id ) ; } const [ backup ] = types . splice ( existingIndex , 1 ) ; try { return this . submit ( { remove : [ id ] , } ) ; } catch ( err ) { this . types ( ) . splice ( existingIndex , 0 , backup ) ; throw err ; } } async update ( prompt ) { const e = prompt && this . types ( ) ?. find ( pp => pp . id === prompt . id ) ; if ( ! e ) { throw new Error ( 'Prompt was not found, id = ' + prompt ?. id ) ; } const backup = { ... e } ; this . updateExisting ( prompt , e ) ; try { return this . submit ( { update : [ prompt ] , } ) ; } catch ( err ) { this . updateExisting ( backup , e ) ; throw err ; } } }