Files
cloud-cap-samples/orders/srv/orders-service.js
Daniel Hutzel 02ea798f5f Streamlined eslint usage for eslint9 w/ cds8 (#719)
* Streamlined eslint usage

* import from @sap/cds instead of @sap/cds/lib

* Using @sap/cds/eslint.js

* eslint.config.mjs aktualisieren

* Adjusted eslint usage for eslint9 with cds8
2024-07-15 14:27:03 +02:00

38 lines
1.3 KiB
JavaScript

const cds = require ('@sap/cds')
class OrdersService extends cds.ApplicationService {
/** register custom handlers */
init(){
const { 'Orders.Items':OrderItems } = this.entities
this.before ('UPDATE', 'Orders', async function(req) {
const { ID, Items } = req.data
if (Items) for (let { product_ID, quantity } of Items) {
const { quantity:before } = await cds.tx(req).run (
SELECT.one.from (OrderItems, oi => oi.quantity) .where ({up__ID:ID, product_ID})
)
if (quantity != before) await this.orderChanged (product_ID, quantity-before)
}
})
this.before ('DELETE', 'Orders', async function(req) {
const { ID } = req.data
const Items = await cds.tx(req).run (
SELECT.from (OrderItems, oi => { oi.product_ID, oi.quantity }) .where ({up__ID:ID})
)
if (Items) await Promise.all (Items.map(it => this.orderChanged (it.product_ID, -it.quantity)))
})
return super.init()
}
/** order changed -> broadcast event */
orderChanged (product, deltaQuantity) {
// Emit events to inform subscribers about changes in orders
console.log ('> emitting:', 'OrderChanged', { product, deltaQuantity }) // eslint-disable-line no-console
return this.emit ('OrderChanged', { product, deltaQuantity })
}
}
module.exports = OrdersService