-
Notifications
You must be signed in to change notification settings - Fork 510
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
24 additions
and
19 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,29 +1,34 @@ | ||
const cds = require('@sap/cds') | ||
module.exports = class CatalogService extends cds.ApplicationService { init() { | ||
|
||
class CatalogService extends cds.ApplicationService { init(){ | ||
|
||
const { Books } = cds.entities ('sap.capire.bookshop') | ||
const { Books } = cds.entities('sap.capire.bookshop') | ||
const { ListOfBooks } = this.entities | ||
|
||
// Add some discount for overstocked books | ||
this.after('READ', ListOfBooks, each => { | ||
if (each.stock > 111) each.title += ` -- 11% discount!` | ||
}) | ||
|
||
// Reduce stock of ordered books if available stock suffices | ||
this.on ('submitOrder', async req => { | ||
const {book,quantity} = req.data | ||
if (quantity < 1) return req.reject (400,`quantity has to be 1 or more`) | ||
let b = await SELECT `stock` .from (Books,book) | ||
if (!b) return req.error (404,`Book #${book} doesn't exist`) | ||
let {stock} = b | ||
if (quantity > stock) return req.reject (409,`${quantity} exceeds stock for book #${book}`) | ||
await UPDATE (Books,book) .with ({ stock: stock -= quantity }) | ||
await this.emit ('OrderedBook', { book, quantity, buyer:req.user.id }) | ||
return { stock } | ||
this.on('submitOrder', async req => { | ||
let { book:id, quantity } = req.data | ||
let book = await SELECT.from (Books, id, b => b.stock) | ||
|
||
// Validate input data | ||
if (!book) return req.error (404, `Book #${id} doesn't exist`) | ||
if (quantity < 1) return req.error (400, `quantity has to be 1 or more`) | ||
if (quantity > book.stock) return req.error (409, `${quantity} exceeds stock for book #${id}`) | ||
|
||
// Reduce stock in database and return updated stock value | ||
await UPDATE (Books, id) .with ({ stock: book.stock -= quantity }) | ||
return book | ||
}) | ||
|
||
// Add some discount for overstocked books | ||
this.after ('READ', ListOfBooks, each => { | ||
if (each.stock > 111) each.title += ` -- 11% discount!` | ||
// Emit event when an order has been submitted | ||
this.after('submitOrder', async (_,req) => { | ||
let { book, quantity } = req.data | ||
await this.emit('OrderedBook', { book, quantity, buyer: req.user.id }) | ||
}) | ||
|
||
// Delegate requests to the underlying generic service | ||
return super.init() | ||
}} | ||
|
||
module.exports = { CatalogService } |