This commit is contained in:
D065023
2019-11-29 12:11:29 +01:00
parent c2d0fba1d8
commit 8f3d112558

View File

@@ -2,25 +2,42 @@ const cds = require('@sap/cds')
const { Books } = cds.entities const { Books } = cds.entities
/** Service implementation for CatalogService */ /** Service implementation for CatalogService */
module.exports = cds.service.impl(function() { module.exports = cds.service.impl(function () {
this.after ('READ', 'Books', each => each.stock > 111 && _addDiscount2(each,11)) this.after(
this.before ('CREATE', 'Orders', _reduceStock) 'READ',
'Books',
each => each.stock > 111 && _addDiscount2(each, 11)
)
this.before('CREATE', 'Orders', _reduceStock)
}) })
/** Add some discount for overstocked books */ /** Add some discount for overstocked books */
function _addDiscount2 (each,discount) { function _addDiscount2 (each, discount) {
each.title += ` -- ${discount}% discount!` each.title += ` -- ${discount}% discount!`
} }
/** Reduce stock of ordered books if available stock suffices */ /** Reduce stock of ordered books if available stock suffices */
async function _reduceStock (req) { async function _reduceStock (req) {
const { Items: OrderItems } = req.data const { Items: OrderItems } = req.data
return cds.transaction(req) .run (()=> OrderItems.map (order => return cds
UPDATE (Books) .set ('stock -=', order.amount) .transaction(req)
.where ('ID =', order.book_ID) .and ('stock >=', order.amount) .run(() =>
)) .then (all => all.forEach ((affectedRows,i) => { OrderItems.map(order =>
if (affectedRows === 0) req.error (409, UPDATE(Books)
`${OrderItems[i].amount} exceeds stock for book #${OrderItems[i].book_ID}` .set('stock -=', order.amount)
.where('ID =', order.book_ID)
.and('stock >=', order.amount)
)
)
.then(all =>
all.forEach((affectedRows, i) => {
if (affectedRows === 0)
req.error(
409,
`${OrderItems[i].amount} exceeds stock for book #${
OrderItems[i].book_ID
}`
)
})
) )
}))
} }