Documented impl

This commit is contained in:
Daniel
2020-12-30 18:48:35 +01:00
parent 81897a3d7e
commit 9fe79b28d6

View File

@@ -1,25 +1,30 @@
const cds = require('@sap/cds') const cds = require('@sap/cds')
const { Books } = cds.entities ('sap.capire.bookshop')
class CatalogService extends cds.ApplicationService { init(){ class CatalogService extends cds.ApplicationService { init(){
// Reflect entities from model
const { Books } = cds.entities ('sap.capire.bookshop')
// Reduce stock of ordered books if available stock suffices // Reduce stock of ordered books if available stock suffices
this.on ('submitOrder', async req => { this.on ('submitOrder', async req => {
const {book,amount} = req.data const {book,amount} = req.data
let {stock} = await SELECT('stock').from(Books,book) // Read stock from database
let {stock} = await SELECT.from (Books, book, b => b.stock)
if (stock >= amount) { if (stock >= amount) {
await UPDATE (Books,book).with ({ stock: stock -= amount }) // Reduce stock by ordered amount
await UPDATE (Books,book) .with ({ stock: stock -= amount })
// Emit event to inform others
await this.emit ('OrderedBook', { book, amount, buyer:req.user.id }) await this.emit ('OrderedBook', { book, amount, buyer:req.user.id })
return { stock } // Return reduced stock to caller
return req.reply ({ stock })
} }
// Return error about insufficient stock
else return req.error (409,`${amount} exceeds stock for book #${book}`) else return req.error (409,`${amount} exceeds stock for book #${book}`)
}) })
// Add some discount for overstocked books // Add some discount for overstocked books
this.after ('READ','Books', each => { this.after ('READ','Books', each => {
if (each.stock > 111) { if (each.stock > 111) each.title += ` -- 11% discount!`
each.title += ` -- 11% discount!`
}
}) })
return super.init() return super.init()