/**
 *
 * Guard logic for each model type to ensure we add and update properly
 * Add a guard for each type (ex: Customer) in your model.
 */ import { Customer } from './customer' ; import { LineItem } from './line-item' ; import { Order } from './order' ; import { Product } from './product' ; import { EntityCache } from './entity-cache' ; param entity param isAdd param cache returns type EntityGuardFn = ( entity : { } , isAdd ? : boolean , cache ? : EntityCache ) => { } ; /** An object with guard functions for each entity collection in the model. */ export const modelGuards = { customers : customerGuard , lineItems : lineItemGuard , orders : orderGuard , products : productGuard } ; /** Ensure customer has only the allowed properties. */ function customerGuard ( customer ) { const { id , first , last , city , birthDate , photo , isDeleted , pet } = customer ; return { id , first , last , city , birthDate , photo , isDeleted , pet } ; } /** Ensure LineItem has only allowed props and the orderId and productId link to an Order and Product in cache. */ function lineItemGuard ( lineItem , isAdd , cache ) { const { id , orderId , productId , quantity , isDeleted : isRemoved } = lineItem ; if ( isAdd ) { const bad = null == cache . orders . find ( o => o . id === orderId ) || null == cache . products . find ( p => p . id === productId ) ; if ( bad ) { throw new Error ( 'LineItem foreign keys not found in cached orders or products' ) ; } return { id , orderId , productId , quantity , isDeleted : isRemoved } ; } else { return { id , quantity , isDeleted : isRemoved } ; } } /** Ensure Order has only allowed props and the customerId inks to a Customer in cache. */ function orderGuard ( order , isAdd , cache ) { const { id , customerId , memo , orderDate } = order ; if ( isAdd ) { const bad = isAdd && null == cache . customers . find ( c => c . id === customerId ) ; if ( bad ) { throw new Error ( `Order.customerId (${ customerId }) not found in cached customers` ) ; } return { id , customerId , memo , orderDate } ; } else { return { id , memo , orderDate } ; } } /** Ensure Product has only the allowed properties. */ function productGuard ( product ) { const { id , productName : name , price } = product ; return { id , productName : name , price } ; }