Firebase get an specific key

i have a realtime-database with the following structure:

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

i am using firebase-functions that gets executed when a new log gets written

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

i have other functions that i want to referenciate to the same location as the one with a new 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
}  

putting the location manually on all 3 functions makes it work just fine but i don't know how to make it listen for the same event on all the locations ( 0, 1 and 2 ) and possibly more locations in the future

So my question: is there a way i can get the location key when a log gets written to any location so i can send it to the other functions

Upvotes: 1

Views: 45

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599401

To listen to all locations, use a parameter in the path that triggers the function:

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

You can then get the parameters from context.params and pass it on:

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

Also see the Cloud Functions for Firebase documentation on handling event data.

Upvotes: 2

Related Questions