我有一个Google Cloud Bucket,Firebase在那里写了我的应用程序数据。我想监视我的数据,并通过文本或电子邮件将新的更新(写入)写入我的Firebase数据库。我目前在Nodejs上设置了Twilio以在Firebase上发送文本,我的代码是:
const functions = require('firebase-functions');
var twilio = require('twilio');
const admin = require('firebase-admin');
admin.initializeApp();
var accountSid = 'account id'; // Account SID from www.twilio.com/console
var authToken = 'account token'; // Auth Token from www.twilio.com/console
var client = new twilio(accountSid, authToken);
exports.useWildcard = functions.firestore
.document('comments/{commentContent}')
.onWrite((change, context) => {
client.messages.create({
body: context.params.commentContent,
to: '+15555555555', // Text this number
from: '+15555555556' // From a valid Twilio number
})
.then((message) => console.log(message.sid));
});
目前,我只想将其构建为注释文档,该文档是通过firefire内部组织的comments/{commentContent}
。后来,我想扩展到其他树木。但是,我不确定每次写入我的注释树时上述操作是否都会运行。是否需要firebase-admin
我上面提到的模块?谢谢!
是的,该onWrite
方法不仅会在写入注释树时运行,而且还会因任何文档中的任何更改以及文档的删除而触发。这意味着现在您的代码将对上述任何情况做出相同的响应,这可能会导致问题,尤其是在文档被删除的情况下,因为它会尝试发送不存在的注释,并且可能会一些空异常。
说您有不同的解决方案。如果您只希望函数对新注释做出反应,而不对更新或删除做出反应,则应使用onCreate
Trigger而不是onWrite
。
如果您还想处理评论更新通知,则可以同时使用onCreate
和onUpdate
,但可以通过以下方式发送不同的消息:
exports.useWildcardCreate = functions.firestore
.document('comments/{commentContent}')
.onCreate((change, context) => {
client.messages.create({
body: context.params.commentContent,
to: '+15555555555', // Text this number
from: '+15555555556' // From a valid Twilio number
})
.then((message) => console.log(message.sid));
});
exports.useWildcardUpdate = functions.firestore
.document('comments/{commentContent}')
.onUpdate((change, context) => {
const newComment = change.after.data();
const previuosComment = change.before.data();
client.messages.create({
body: 'The comment ${previuosComment} has been changed to ${newComment}',
to: '+15555555555', // Text this number
from: '+15555555556' // From a valid Twilio number
})
.then((message) => console.log(message.sid));
});
最后,如果您还需要通知何时删除评论,则应使用onWrite
方法,但要区分3种不同情况,如下所示:
exports.useWildcard = functions.firestore
.document('comments/{commentContent}')
.onWrite((change, context) => {
var textBody;
const oldComment = change.before.data();
const newComment = change.after.data();
if (change.after.exists == false) { // comment has been deleted
textBody = 'The comment ${oldComment} has been deleted';
}
else if (oldComment != newComment) { // comment has been updated
textBody = 'The comment ${oldComment} has been changed to ${newComment}';
}
else { // if its not an update or a deletion its a new comment
textBody = newComment;
}
client.messages.create({
body: textBody,
to: '+15555555555', // Text this number
from: '+15555555556' // From a valid Twilio number
})
.then((message) => console.log(message.sid));
});
最后require('firebase-admin')
是必需的,因为它将允许您从特权环境中与Firebase进行交互。在这里您可以找到Firebase Admin SDK的所有信息
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句