首页 文章

Firebase函数 - 写入数据库

提问于
浏览
0

我对Firebase Functions和node.js非常陌生,我需要帮助编写一个完成以下工作流程的函数 .

1:在“/ dir1 / / dir2 / ”收听写事件 .

2:从“/ dir1 / / dir2 / dir3”目录中读取数据 .

2.5:对于“/ dir1 / / dir2 / dir3”中的每个项目,获取密钥 .

3:对于每个密钥,将原始写入的数据“克隆”为“/ dir4 / / dir5 / ” .

我怎样才能做到这一点?提前致谢!

1 回答

  • 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);
              });
          }
        })
    

相关问题