rm complexity

This commit is contained in:
D065023
2020-01-28 15:21:46 +01:00
parent b632013b16
commit 43d0373d70

View File

@@ -2,27 +2,26 @@ const cds = require('@sap/cds')
const { Books } = cds.entities
/** Service implementation for CatalogService */
module.exports = cds.service.impl(async function() {
module.exports = cds.service.impl(async function () {
const bupaSrv = await cds.connect.to('API_BUSINESS_PARTNER')
const { A_BusinessPartnerAddress } = bupaSrv.entities
this.after ('READ', 'Books', each => each.stock > 111 && _addDiscount2(each,11))
this.before ('CREATE', 'Orders', _reduceStock)
this.on('READ', 'Addresses', req => bupaSrv.run(req.query.from(A_BusinessPartnerAddress)))
this.after('READ', 'Books', each => each.stock > 111 && _addDiscount2(each, 11))
this.before('CREATE', 'Orders', _reduceStock)
this.on('READ', 'Addresses', req => bupaSrv.tx(req).run(req.query))
})
/** Add some discount for overstocked books */
function _addDiscount2 (each,discount) {
function _addDiscount2(each, discount) {
each.title += ` -- ${discount}% discount!`
}
/** Reduce stock of ordered books if available stock suffices */
async function _reduceStock (req) {
async function _reduceStock(req) {
const { Items: OrderItems } = req.data
return cds.transaction(req) .run (()=> OrderItems.map (order =>
UPDATE (Books) .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,
return cds.transaction(req).run(() => OrderItems.map(order =>
UPDATE(Books).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}`
)
}))