【发布时间】:2021-11-11 19:18:27
【问题描述】:
我有一个触发 API 的 onCreate 云函数,但我需要确保它不会触发两次。云函数触发器可以执行多次,我们鼓励使用 eventId 来实现幂等性。这是我目前拥有的:
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
})
这就是我所关心的。根据docs,如果文档的内容受到并发操作的影响,firestore 事务将再次运行。在这种情况下,如果它“再次运行”,它将再次运行 axios 调用,这对我不利。
如果云函数触发器(在本例中为 onCreate)运行多次,它是否有可能并发并导致竞争条件?如果是这样,那么 axios 请求可能会多次发出,这是我必须避免的。
提前感谢您的帮助。
【问题讨论】:
标签: node.js firebase google-cloud-firestore google-cloud-functions