new messaging

This commit is contained in:
D065023
2020-09-15 15:30:14 +02:00
parent 6fdd91b8c8
commit a71aaf75a1
8 changed files with 17 additions and 22 deletions

View File

@@ -7,7 +7,7 @@
"index.cds"
],
"dependencies": {
"@sap/cds": ">=3.33.1",
"@sap/cds": "^4",
"express": "^4.17.1"
},
"scripts": {

View File

@@ -2,17 +2,10 @@ using { sap.capire.reviews as my } from '../db/schema';
service ReviewsService {
// Sync API
entity Reviews as projection on my.Reviews excluding { likes }
action like (review: type of Reviews:ID);
action unlike (review: type of Reviews:ID);
// Async API
event reviewed : {
subject: type of Reviews:subject;
rating: Decimal(2,1)
};
// Input validation
annotate Reviews with {
subject @mandatory;

View File

@@ -1,25 +1,24 @@
const cds = require ('@sap/cds')
module.exports = cds.service.impl (function(){
module.exports = cds.service.impl (async function(){
// Get the CSN definition for Reviews from the db schema for sub-sequent queries
// ( Note: we explicitly specify the namespace to support embedded reuse )
const { Reviews, Likes } = this.entities ('sap.capire.reviews')
const messaging = await cds.connect.to('messaging')
this.before (['CREATE','UPDATE'], 'Reviews', req => {
if (!req.data.rating) req.data.rating = Math.round(Math.random()*4)+1
})
// Emit an event to inform subscribers about new avg ratings for reviewed subjects
// ( Note: req.on.succeeded ensures we only do that if there's no error )
this.after (['CREATE','UPDATE','DELETE'], 'Reviews', async(_,req) => {
const {subject} = req.data
const {rating} = await cds.transaction(req) .run (
SELECT.one (['round(avg(rating),2) as rating']) .from (Reviews) .where ({subject})
)
req.on ('succeeded', ()=>{
global.it || console.log ('< emitting:', 'reviewed', { subject, rating })
this.emit ('reviewed', { subject, rating })
})
const msgTx = messaging.tx(req)
global.it || console.log ('< emitting:', 'reviewed', { subject, rating })
msgTx.emit ('review/reviewed', { subject, rating })
})
// Increment counter for reviews considered helpful