【发布时间】:2019-10-12 09:08:41
【问题描述】:
我根本看不出我在哪里出错了。我的 Cloud Firestore 位于“europe-west3”,功能部署到“europe-west1”(文档告诉我这是离 west3 最近的位置)。
结构是这样的:我有一堆“票”,每个票都可以有一个名为“cmets”的子集合。控制台因此看起来像这样:
上传成功:
功能代码取自官方代码示例 Github repo for Function samples
这是我的代码的样子:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.countComments = functions.region('europe-west1').database.ref('/tickets/{ticketId}/comments/{commentsid}')
.onWrite(
async (change) => {
const ticketsRef = change.after.ref.parent;
const countRef = ticketsRef.parent.child('comments_count');
let increment;
if(change.after.exists() && !change.before.exists()) {
increment = 1;
} else if(!change.after.exists() && change.before.exists()) {
increment = -1;
} else {
return null;
}
await countRef.transaction((current) => {
return (current || 0) + increment;
});
console.log('Counter updated');
return null;
});
exports.recountComments = functions.region('europe-west1').database.ref('/tickets/{ticketId}/comments_count')
.onDelete(
async (snap) => {
const counterRef = snap.ref;
const collectionRef = counterRef.parent.child('comments');
const commentsData = await collectionRef.once('value');
return await counterRef.set(commentsData.numChildren());
}
)
现在,问题是这些函数根本不会触发。无论我是通过客户端(Flutter 应用)推送更改还是直接在 Firebase 控制台中更改内容,我都没有在日志中看到任何内容。
在我绝望的情况下,我还尝试简单地听“/tickets”,因为该路径下方的任何更改也应该触发 - 但什么都没有。
所以。我忽略了什么明显的事情?而且,是的,我看了其他问题/答案,但没有什么让我大吃一惊...
编辑:
这将是更正的版本,可能不是最佳的。
exports.countComments = functions.region('europe-west1').firestore.document('/tickets/{ticketId}/comments/{commentsId}')
.onWrite(
async (change, context) => {
const ticketId = context.params.ticketId;
const ticketRef = admin.firestore().collection('tickets').doc(ticketId);
let increment;
if(change.after.exists && !change.before.exists) {
increment = 1;
} else if(!change.after.exists && change.before.exists) {
increment = -1;
} else {
return null;
}
return transaction = admin.firestore().runTransaction(t => {
return t.get(ticketRef)
.then(doc => {
let count = (doc.data().comments_count || 0) + increment;
t.update(ticketRef, {comments_count: count});
});
}).then(res => {
console.log('Counter updated');
}).catch(err => {
console.log('Transaction error:', err);
});
});
【问题讨论】:
标签: javascript firebase google-cloud-firestore google-cloud-functions