【问题标题】:Firebase get an specific keyFirebase 获取特定密钥
【发布时间】:2019-02-19 20:11:12
【问题描述】:

我有一个realtime-database,其结构如下:

-- test-b7a6b
    -- locations
        -- 0
            -- logs
                -- alarm_2a330b56-c1b8-4720-902b-df89b82ae13a                
                ...
            -- devices
            -- deviceTokens
        -- 1
        -- 2

我正在使用firebase-functions,它会在写入新日志时执行

let functions = require('firebase-functions');
let admin = require('firebase-admin');

admin.initializeApp(functions.config().firebase);

exports.sendPush = functions.database.ref('/locations/0/logs/{devicelogs}/{logs}').onWrite((change, context) => {
  let logsData = change.after.val();
  loadUsers();
  getBody(deviceTypeId);
  //managing the results
});

我有其他功能要引用到与具有新 log 的功能相同的位置

function loadUsers() {
    let dbRef = admin.database().ref('/locations/0/deviceTokens');
    //managing users
}

function getBody(deviceTypeId) {
  let devicesDB = admin.database().ref('/locations/0/devices');
  //managing devices
}  

在所有 3 个功能上手动放置位置使其工作正常,但我不知道如何让它在所有位置(0、1 和 2)上侦听相同的事件,并且未来可能会有更多地点

所以我的问题是:有没有办法在将日志写入任何位置时获取位置键,以便我可以将其发送到其他功能

【问题讨论】:

    标签: javascript firebase firebase-realtime-database google-cloud-functions


    【解决方案1】:

    要监听所有位置,在触发函数的路径中使用参数:

    exports.sendPush = functions.database.ref('/locations/{location}/logs/{devicelogs}/{logs}').onWrite((change, context) => {
    

    然后您可以从context.params 获取参数并将其传递:

    exports.sendPush = functions.database.ref('/locations/{location}/logs/{devicelogs}/{logs}').onWrite((change, context) => {
      let logsData = change.after.val();
      loadUsers(context.params.location);
      getBody(deviceTypeId);
      //managing the results
    });
    

    另见Cloud Functions for Firebase documentation on handling event data

    【讨论】:

      猜你喜欢
      • 2019-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-26
      • 2017-09-15
      • 2019-01-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多