1

I have a feature in my testing application that allows users to submit text-based data and one image file per said "data collection". I have the following code to store both data:

let rtdbRef = firebase.database().ref().child('someNode').push();
let pushedKey = rtdbRef.key;

rtdbRef.set({
  someKey: someValue
})
.catch((e) => {
  //Handle error;
});

let storageRef = firebase.database().ref().child('images/' + pushedKey);
storage.put(myFile).then((snapshot) => {
  console.log('File upload successful');
}).catch((e) => {
  //Handle error;
});

As you can see, I'm uploading the data with two separate Promise chains. So, I changed it to the following:

let rtdbRef = firebase.database().ref().child('someNode').push();
let pushedKey = rtdbRef.key;
let storageRef = firebase.database().ref().child('images/' + pushedKey);

rtdbRef.set({
  someKey: someValue
})
.then({
    return storageRef.put(myFile).then((snapshot) => snapshot);
})
.catch((e) => {
  //Handle error;
});

I changed my initial code because I thought that there might be a chance where my text-based data gets stored and yet my image file upload fails. However, it seems like changing my initial code to the second one does not make anything better:

  • If I separate the two chains, doesn't that mean that I'm sending both my text-based data and image file simultaneously, which makes it faster? If the answer is yes, should I stick to my initial code?
  • My initial concern persists: what if the text-based data gets sent successfully and yet the image file upload fails. How do I make it so that if any of my two attempts to store data fails, I cancel the whole data storing operation?
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Richard
  • 7,037
  • 2
  • 23
  • 76
  • You're calling two separate backend services, and there is no support for a transaction running across these services. You will have to deal with potential partial data by: 1) making your code robust, and 2) running periodic cleanup scripts. See my answer here: https://stackoverflow.com/questions/47319764/firebase-handle-sudden-loss-in-connection/47322207#47322207 – Frank van Puffelen May 04 '19 at 04:17
  • @FrankvanPuffelen I see. So basically, like the code in the link you provided, is it better to wait for the file upload to finish before pushing my text-based data (I'm assuming here that text-based data is less prone to failures)? Also, how do I run *regular batch processes to cleanup data*? – Richard May 04 '19 at 04:27
  • There is no definitive 'better' here. You just have to make sure that your code that reads the data can handle all of the cases. I typically run cleanup code on Cloud Functions, or with a local Node.js script that I run when I have a moment. – Frank van Puffelen May 04 '19 at 13:50

0 Answers0