【发布时间】:2018-12-11 19:34:46
【问题描述】:
我有一个Cloud Firestore trigger,负责在我的应用中调整用户钱包的余额。
exports.onCreateTransaction = functions.firestore
.document('accounts/{accountId}/transactions/{transactionId}')
.onCreate(async (snap, context) => {
const { accountId, transactionId } = context.params;
const transaction = snap.data();
// See the implementation of alreadyTriggered in the next code block
const alreadyTriggered = await firestoreHelpers.triggers.alreadyTriggered(context);
if (alreadyTriggered) {
return null;
}
if (transaction.status === 'confirmed') {
const accountRef = firestore
.collection('accounts')
.doc(accountId);
const account = (await accountRef.get()).data();
const balance = transaction.type === 'deposit' ?
account.balance + transaction.amount :
account.balance - transaction.amount;
await accountRef.update({ balance });
}
return snap.ref.update({ id: transactionId });
});
作为触发器实际上可能是be called more than once,我添加了这个alreadyTriggered 辅助函数:
const alreadyTriggered = (event) => {
return firestore.runTransaction(async transaction => {
const { eventId } = event;
const metaEventRef = firestore.doc(`metaEvents/${eventId}`);
const metaEvent = await transaction.get(metaEventRef);
if (metaEvent.exists) {
console.error(`Already triggered function for event: ${eventId}`);
return true;
} else {
await transaction.set(metaEventRef, event);
return false;
}
})
};
大多数情况下,一切都按预期进行。但是,今天我收到一个超时错误,导致数据库中的数据不一致。
函数执行耗时 60005 毫秒,完成状态为:'timeout'
这个超时的原因是什么?以及如何确保它不再发生,以便我的交易金额成功反映在账户余额中?
【问题讨论】:
标签: node.js firebase google-cloud-firestore google-cloud-functions