Updated to use srv-to-srv + declared events
This commit is contained in:
@@ -2,10 +2,17 @@ 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;
|
||||
|
||||
@@ -4,27 +4,26 @@ 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
|
||||
this.after (['CREATE','UPDATE','DELETE'], 'Reviews', async(_,req) => {
|
||||
this.after (['CREATE','UPDATE','DELETE'], 'Reviews', async function(_,req) {
|
||||
const {subject} = req.data
|
||||
const {rating} = await cds.transaction(req) .run (
|
||||
const {rating} = await cds.tx(req) .run (
|
||||
SELECT.one (['round(avg(rating),2) as rating']) .from (Reviews) .where ({subject})
|
||||
)
|
||||
global.it || console.log ('< emitting:', 'reviewed', { subject, rating })
|
||||
messaging.tx(req).emit ('reviewed', { subject, rating })
|
||||
this.emit ('reviewed', { subject, rating })
|
||||
})
|
||||
|
||||
// Increment counter for reviews considered helpful
|
||||
this.on ('like', (req) => {
|
||||
if (!req.user) return req.reject(400, 'You must be identified to like a review')
|
||||
const {review} = req.data, {user} = req
|
||||
const tx = cds.transaction(req)
|
||||
const tx = cds.tx(req)
|
||||
return tx.run ([
|
||||
INSERT.into (Likes) .entries ({review_ID: review, user: user.id}),
|
||||
UPDATE (Reviews) .set({liked: {'+=': 1}}) .where({ID:review})
|
||||
@@ -35,7 +34,7 @@ module.exports = cds.service.impl (async function(){
|
||||
this.on ('unlike', async (req) => {
|
||||
if (!req.user) return req.reject(400, 'You must be identified to remove a former like of yours')
|
||||
const {review} = req.data, {user} = req
|
||||
const tx = cds.transaction(req)
|
||||
const tx = cds.tx(req)
|
||||
const affectedRows = await tx.run (DELETE.from (Likes) .where ({review_ID: review,user: user.id}))
|
||||
if (affectedRows === 1) return tx.run (UPDATE (Reviews) .set ({liked: {'-=': 1}}) .where ({ID:review}))
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user