代码之家  ›  专栏  ›  技术社区  ›  Kento Nishi

firebase函数-写入数据库

  •  0
  • Kento Nishi  · 技术社区  · 6 年前

    我对firebase函数和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}”的数据。

    我该怎么做?提前谢谢!

    1 回复  |  直到 6 年前
        1
  •  2
  •   James Poag    6 年前
    // 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);
              });
          }
        })