cleaned up

This commit is contained in:
Daniel
2020-03-02 08:29:49 +01:00
parent cb066233c9
commit c6eb21ec51
26 changed files with 140 additions and 122 deletions

View File

@@ -3,5 +3,4 @@ using { sap.capire.bookshop as my } from '../db/schema';
service AdminService @(_requires:'authenticated-user') {
entity Books as projection on my.Books;
entity Authors as projection on my.Authors;
entity Orders as select from my.Orders;
}

View File

@@ -1,13 +1,12 @@
using { sap.capire.bookshop as my } from '../db/schema';
@path:'/browse'
service CatalogService {
service CatalogService @(path:'/browse') {
@readonly entity Books as SELECT from my.Books {*,
author.name as author
} excluding { createdBy, modifiedBy };
@requires_: 'authenticated-user'
@insertonly entity Orders as projection on my.Orders;
action order (book : Books.ID, amount: Integer);
}

View File

@@ -1,26 +1,23 @@
const cds = require('@sap/cds')
const { Books } = cds.entities
/** Service implementation for CatalogService */
module.exports = cds.service.impl(function() {
this.after ('READ', 'Books', each => each.stock > 111 && _addDiscount2(each,11))
this.before ('CREATE', 'Orders', _reduceStock)
module.exports = cds.service.impl (function() {
// Get entity definitions from reflected model
const { Books } = cds.entities
// Add some discount for overstocked books
this.after ('READ', 'Books', each => {
if (each.stock > 111) each.title += ` -- 11% discount!`
})
// Reduce stock of ordered books if available stock suffices
this.on ('order', async (req) => {
const {UPDATE} = cds.ql(req), {book,amount} = req.data
const n = await UPDATE (Books, book)
.where ('stock >=', amount)
.set ('stock -=', amount)
n > 0 || req.error (409,`${amount} exceeds stock for book #${book}`)
})
})
/** Add some discount for overstocked books */
function _addDiscount2 (each,discount) {
each.title += ` -- ${discount}% discount!`
}
/** Reduce stock of ordered books if available stock suffices */
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,
`${OrderItems[i].amount} exceeds stock for book #${OrderItems[i].book_ID}`
)
}))
}