Zephania Mwando
Zephania Mwando

Reputation: 118

Calculating product rating

A new value should be added as productRating under the product nodeI am trying to calculate the product rating for my products in my realtime database using a firebase cloud function. What am I missing since am getting errors in the logs after deploying

I have deployed the code but still on rating added no change happens


    const functions = require('firebase-functions');

    const admin = require('firebase-admin');
    admin.initializeApp(functions.config().firebase);

    //firebase db calculations for rating average
    exports.productAverage = functions.database.ref('/Products/{product_id}/rating')
        .onCreate((snapshot, context) => {
            return admin.database().ref('/Products/{product_id}/rating').once('value')
                .then((snapshot) => {
                    let sum = 0;
                    snapshot.forEach(child => {
                        sum = sum + child.val();
                    });
                    let productRating = sum / snapshot.numChildren();

                    return admin.database().ref('/Products/{product_id}').child('productRating').set(productRating);
                });
        });

I expect each time a productRating node is added, the average updates a node on the database with productRating

Upvotes: 1

Views: 121

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599121

There are a few things that immediately jump out:

  1. You're triggering on onCreate. But you want to recalculate the average whenever any rating is added (or removed or updated), you'll want to trigger on onWrite.
  2. You're reloading the same data in your function that is pass in already. That is wasteful, so let's remove that.

With these two changes, you'd end up with something like:

exports.productAverage = functions.database.ref('/Products/{product_id}/rating')
    .onWrite((change, context) => {
        let snapshot = change.after;

        let sum = 0;
        snapshot.forEach(child => {
            sum = sum + child.val();
        });
        let productRating = sum / snapshot.numChildren();

        return snapshot.ref.parent.child('productRating').set(productRating);
    });

Upvotes: 3

Related Questions