【发布时间】:2019-07-14 09:24:24
【问题描述】:
好的,我将从一些背景开始(跳到 MY ISSUE for tl;dr):
我有一个正在开发中的应用程序,它以二维数组的形式将数据从 Google 表格传递到 Firebase 实时数据库。 Google sheet的数据布局如下图:
此数据通过如下所示的 Apps 脚本函数结果传递到节点 masterSheet 下的 Firebase 实时数据库:
它用作我正在使用 Ionic 框架开发的移动 Web 应用程序的实时数据库(预览如下):
我有处理在每个作业的子任务的正确位置设置“Y”和“N”标志的功能,以及在所有子任务时将整体作业完成状态标志设置为“Y”的功能已按预期工作。
我正在尝试通过 Firebase Cloud Functions 添加自动电子邮件服务,每当作业的整体“已完成”状态设置为“Y”(即参考值:'masterSheet/ 0/1' 等于 "Y")。
到目前为止,每当作业的总体完成状态从“N”更改为通过 onUpdate() 方法和要监听的位置的 .ref() 到“Y”。
下面是我的 Index.js 文件,其中包含我正在使用的云功能:
// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');
// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp();
// The mail service used
const nodemailer = require('nodemailer');
// Cloud Fucntion to export:
exports.onMessageUpdate = functions.database.ref('/masterSheet/{subArray}/1')
.onUpdate((change) => {
var changeRef = change.after.ref.path;
console.log('changeRef: ' + changeRef);
var newVal = change.after.val();
if (newVal == "Y"){
getUsers();
}
})
// Fucntion to get all registers users of the Firebase Project
function getUsers(){
var userEmails = [];
admin.auth().listUsers()
.then(function(listUsersResult) {
listUsersResult.users.forEach(function(userRecord) {
console.log(userRecord);
userEmails.push(userRecord.email);
sendCompletionEmail(userRecord.email)
});
})
.catch(function(error) {
console.log("Error listing users:", error);
});
}
// Function to send automatic emails
function sendCompletionEmail(email){
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
type: 'OAuth2',
user: 'xxxxxxxx@gmail.com',
clientId: 'xxxxxxxx.apps.googleusercontent.com',
clientSecret: 'xxxxxxxxxxxxxxx',
refreshToken: 'xxxxxxxxxxxxxx'
}
})
// Email details:
var mailOptions = {
from: 'xxxxxxx',
to: email,
subject: 'Job completion notification',
text: 'This is an automated message to inform you that a job has been fully completed ' +
'with all of its tasks marked as done. \n\nYou can view this (along with any others) from the Completed ' +
'Jobs page within the app.'
}
transporter.sendMail(mailOptions, function (err, res) {
if(err){
console.log('Error');
} else {
console.log('Email Sent');
}
})
}
我的问题: 我希望能够在发送的这封自动电子邮件中包含职位。
记录下sn-p中使用的change.after.ref.path的结果:
// Cloud Fucntion to export:
exports.onMessageUpdate = functions.database.ref('/masterSheet/{subArray}/1')
.onUpdate((change) => {
var changeRef = change.after.ref.path;
console.log('changeRef: ' + changeRef);
var newVal = change.after.val();
if (newVal == "Y"){
getUsers();
}
})
产生此日志输出:
其中包含我想要的内容...但我不知道如何将其取出...
如何从 changeRef 变量中检索第二个值,以便将其传递给 sendCompletionEmail() 函数并使用它来引用位置处的项目[0] 为那个节点?
类似:
var subArray = changeRef[1]
获取值:0 out of masterSheet/0/1
我可以将其存储为变量,并用于引用已发送电子邮件中刚刚完成的工作的职位。
感谢您的帮助!
【问题讨论】:
标签: javascript firebase firebase-realtime-database google-cloud-functions