src/ratingservice/server.js
/**
 * Function adds rating for specific product and stores them in simulated db. Empty callback is called.
 */
Function adds rating for specific product and stores them in simulated db. Empty callback is called.
Function adds rating for specific product and stores them in simulated db . Empty callback is called .
function addRating(call, callback) {
  logger.info('received ratings request');
  console.log(call)
  const request = call.request;
  const ratingItem = request.rating;
  const { product_id, rating } = ratingItem;
  if (typeof product_id !== 'string' || rating <= 0 || rating > 5) throw new Error('invalid ratingItem');
  const allRatings = readRatingsFromDb();
  const ratingByProductId = allRatings[product_id];
  let newRating = null;
  if (!ratingByProductId) {
    newRating = { amount: 1, average: rating }
  } else {
    const amount = ratingByProductId.amount;
    const average = ratingByProductId.average;
    newRating = { amount: amount + 1, average: ((average * amount) + rating) / (amount + 1) }
  }
  allRatings[product_id] = newRating;
  writeRatingsToDb(allRatings)
  callback(null, null);
}
function addRating ( call , callback ) { logger . info ( 'received ratings request' ) ; console . log ( call ) const request = call . request ; const ratingItem = request . rating ; const { product_id , rating } = ratingItem ; if ( typeof product_id !== 'string' || rating <= 0 || rating > 5 ) throw new Error ( 'invalid ratingItem' ) ; const allRatings = readRatingsFromDb ( ) ; const ratingByProductId = allRatings [ product_id ] ; let newRating = null ; if ( ! ratingByProductId ) { newRating = { amount : 1 , average : rating } } else { const amount = ratingByProductId . amount ; const average = ratingByProductId . average ; newRating = { amount : amount + 1 , average : ( ( average * amount ) + rating ) / ( amount + 1 ) } } allRatings [ product_id ] = newRating ; writeRatingsToDb ( allRatings ) callback ( null , null ) ; }
Function adds rating for specific product and stores them in simulated db.
Function adds rating for specific product and stores them in simulated db .