我对Firebase Functions和node.js极为陌生,我需要帮助编写一个完成以下工作流程的函数。
1:在“ / dir1 / {PUSH-ID} / dir2 / {MESSAGE-ID}”处侦听写事件。
2:从“ / dir1 / {PUSH-ID} / dir2 / dir3”目录中读取数据。
2.5:对于“ / dir1 / {PUSH-ID} / dir2 / dir3”中的每个项目,获取密钥。
3:对于每个密钥,将原始写入中的数据“克隆”到“ / dir4 / {key} / dir5 / {MESSAGE-ID}”。
我该怎么做?预先感谢!
答案 0 :(得分:2)
// 1: Listen to a write event at "/dir1/{PUSH-ID}/dir2/{MESSAGE-ID}".
exports.propagateMessages =
functions.database.ref('/dir1/{PUSH_ID}/dir2/{MESSAGE_ID}')
.onWrite((change, context) => {
// Do Nothing when the data is deleted...
if (!change.after.exists()) {
// Perhaps you intend to delete from cloned dirs?
// if so, left as reader's exercise, just follow from below
return null;
}
else {
let pushId = context.params.PUSH_ID;
let messageID = context.params.MESSAGE_ID;
let fireDB = change.after.ref.root;
// 2: Read data from a directory at "/dir1/{PUSH-ID}/dir2/dir3".
return fireDB.child(`/dir1/${pushId}/dir2/dir3`).once('value')
.then(listenersSnapshot => {
let listener_promises = []; // collection of writes
// 2.5: For each item in "/dir1/{PUSH-ID}/dir2/dir3", get the key.
listenersSnapshot.forEach(childSnapshot => {
let child_key = childSnapshot.key;
// 3: For each key, "clone" the data from the original write to "/dir4/{key}/dir5/{MESSAGE-ID}".
listener_promises.push(
fireDB.child(`/dir4/${child_key}/dir5/${messageID}`).set(change.after.val())
);
});
// wait on all writes to complete
return Promise.all(listener_promises);
})
.catch(err => {
console.log(err);
});
}
})