I have an onCreate cloud function that hits an API but I need to be sure that it never hits it twice. Cloud function triggers can execute more than once and we are encouraged to use the eventId for idempotency. Here is what I currently have:
let ship_ref = admin.firestore().collection('shipments').doc(event_id)
return admin.firestore().runTransaction(transaction => {
return transaction.get(ship_ref)
.then(ship_doc => {
if (ship_doc.exists) {
console.log('label already generated')
return null
}
// generate the label
return axios({
method: 'post',
...rest of the axios config
})
.then(label_response => {
const label_data = label_response.data
// add the label data to the shipment collection
transaction.set(ship_ref, {
...sale_data,
label_data,
tracking_url_data,
completed_sale_ref: snap.ref
})
return null
})
.catch(e => {
// handle fail
})
})
})
.then(() => {
// transaction complete
})
.catch(e => {
// error
})
Here is what I am concerned about. As per the docs a firestore transaction will run again if the contents of the document are affected by a concurrent action. In this case if it "runs again" it will run the axios call again and that's bad for me.
If a cloud function trigger (onCreate in this case) runs more than once, is there ever a chance that it will be concurrent and cause a race condition? If so, then it is possible that the axios request could be made more than one time and that's what I have to avoid.
Thank you in advance for your help.