• Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • About
  • Life
  • Tech
  • Travel
  • Work
  • Questions
  • Contact

Welcome

.

Cloud Functions: Avoid Nesting Promises for different conditions

April 11, 2020 by

Questions › Cloud Functions: Avoid Nesting Promises for different conditions
0
Vote Up
Vote Down
Garmaine asked 4 years ago

I am trying to write a function that takes into account 3 conditions whenever Stores/{storeId}/{departmentId}/{productId} gets triggered and write new data in ref.child('Home').child('Chiep').child(departmentId).child(productId).

1) When there is no data in firestore, I need to fill up all the fields in Realtime DB, by making queries in 2 different firestore's nodes: Stores and Products in order to take their images.

2) When a change is made in Stores node and it comes from the same {storeId}, I just need to update some data without making any additional query.

3) And finally, when a change is made in Stores node and it comes from other {storeId}, I need to make only one query in the Stores node.

exports.homeChiepest = functions.firestore
.document('Stores/{storeId}/{departmentId}/{productId}')
.onWrite((change, context) => {

  const storeId = context.params.storeId;
  const departmentId = context.params.departmentId;
  const productId = context.params.productId;
  const ref = admin.database().ref();

  // Get an object with the current document value.
  // If the document does not exist, it has been deleted.
  const document = change.after.exists ? change.after.data() : null;

  // Get an object with the previous document value (for update or delete)
  const oldDocument = change.before.exists ? change.before.data() : null;

  // Prevent infinite loops
  if (!change.after.exists) {
    console.log('DATA DELETED RETURN NULL');
    return null;
  }

  const newPrice = document.price;
  const newTimestamp = document.timestamp;

  return ref.child('Home').child('Chiep')
  .child(departmentId).child(productId)
  .once('value')
  .then(dataSnapshot => {

    if (dataSnapshot.val() !== null) {

      console.log('CHIEP DOES exist');

      const oldPrice = dataSnapshot.val().price;
      const storeKey = dataSnapshot.val().storeKey;
      if (storeId === storeKey) {
        console.log('SAME STORE - Change price and timestamp');
        var newChiepest = {
          timestamp: newTimestamp,
          price: newPrice
        };
        return dataSnapshot.ref.update(newChiepest);

      } else {
        console.log('OTHER STORE - Verify if price is chieper...');
        if (newPrice <= oldPrice) {
          console.log('NEW PRICE: '+newPrice+' is chieper than the older one: '+oldPrice);

          return change.after.ref.parent.parent.get().then(doc => { // HERE Avoid nesting promises
            newStoreImg = doc.data().image;
            var newStoreChiep = {
              price: newPrice,
              storeImg: newStoreImg,
              storeKey: storeId,
              timestamp: newTimestamp
            };
            return dataSnapshot.ref.update(newStoreChiep);

          });

        } else {
          console.log('NEW PRICE: '+newPrice+' is mode EXPENSIVE than the older one: '+oldPrice);
        }
        return null;
      }

    } else {
      console.log('data does NOT exist, so WRITE IT!');

      let getStoreData = change.after.ref.parent.parent.get();
      let getProductData = admin.firestore().collection('Products').doc('Departments').collection(departmentId).doc(productId).get();

      return Promise.all([getStoreData, getProductData]).then(values => { // HERE Avoid nesting promises
        const [store, product] = values;
        var newHomeChiepest = {
          depId: departmentId,
          price: newPrice,
          prodImg: product.data().image,
          prodKey: productId,
          storeKey: storeId,
          storeImg: store.data().image,
          timestamp: newTimestamp
        };
        return dataSnapshot.ref.set(newHomeChiepest);

      });

    }


  })
  .catch(error => {
    console.log('Catch error reading Home: ',departmentId ,'/', productId,'; message: ',error);
    return false;
  });

});

The problem is: different possibilities of querying or not querying another firestore node led me to a warning while uploading the Clound Function, that is:

warning Avoid nesting promises promise/no-nesting

I appreciate any help to refactor this code.

Are you looking for the answer?
Original Question and Possible Answers can be found on `http://stackoverflow.com`

Question Tags: firebase, google-cloud-functions, javascript, promise

Please login or Register to submit your answer




Primary Sidebar

Tags

Advancements best Business strategies commercial convenience economic Finances Cognitive decline Financial growth firm Future Hidden Gems Home hydration Impact Innovations lighting line of work Mental health Must-See New York City office patronage Productivity profession Profitability tips Profit optimization pursuit recreation Revenue enhancement romance sippy cups social station Technological breakthroughs technology toddlers trading transaction Treasures Uncover undertaking Well-being Wonders Work Young onset dementia

Newsletter

Complete the form below, and we'll send you all the latest news.

Footer

Footer Funnies

Who knew that reading the footer could be such a hilarious adventure? As we navigate websites, books, and documents, we often stumble upon the unassuming space at the bottom, only to discover a treasure trove of amusement. In this side-splitting compilation, we present 100 jokes that celebrate the unsung hero of content – the footer. Get ready to chuckle, giggle, and maybe even snort as we dive into the world of footnotes, disclaimers, and hidden comedic gems. Brace yourself for a wild ride through the footer!

Recent

  • Unveiling the Enigma: Almost-Magical Lamp Lights Highway Turns
  • The Impact of Young Onset Dementia on Employment and Finances: Optimizing Post-Diagnostic Approaches
  • 11 Wonders of 2023 Technological Breakthrough – Unveiling the Future
  • Work from Home and Stay Mentally Sane – Achieve Productivity and Well-being
  • Hidden Gems of New York City – Uncover the Must-See Treasures!

Search

Tags

Advancements best Business strategies commercial convenience economic Finances Cognitive decline Financial growth firm Future Hidden Gems Home hydration Impact Innovations lighting line of work Mental health Must-See New York City office patronage Productivity profession Profitability tips Profit optimization pursuit recreation Revenue enhancement romance sippy cups social station Technological breakthroughs technology toddlers trading transaction Treasures Uncover undertaking Well-being Wonders Work Young onset dementia

Copyright © 2023