1

I am using firebase database to store my iOS app data.

enter image description here

I am saving user tracking data in this app which is working fine.

I have to send a push notification to the user (userID = 57411405) using push token which I am saving in 'IOS' field.

This cloud function I am using :

This cloud function is working fine. I am able to track event which save new tracking data. Here is log of this cloud function:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

// Create and Deploy Your First Cloud Functions
// https://firebase.google.com/docs/functions/write-firebase-functions

exports.databasechanges = functions.database.ref('/users/{id}/LocationTracking').onWrite(event =>{

var eventSnapshot = event.data

console.log('UserId - ', event.params.id);

const userID = event.params.id
const root = event.data.ref.root

admin.database().ref('users/{id}/NotificationToken').on('value').then((snapshot) => {

  var token = snapshot.val().IOS;

  console.log('token',token)

  return snapshot.val();
}).catch(error => {
  console.error(error);
  res.error(500);
});

return eventSnapshot.val()

});

But on cloud function console I am getting this error:

enter image description here Now, I am not able to figure out how to access this push token (IOS) and send push notification using cloud function.

Peter Haddad
  • 78,874
  • 25
  • 140
  • 134
ajeet sharma
  • 803
  • 10
  • 37

1 Answers1

4

To get the field "IOS", try this:

//inside the trigger function
admin.database().ref('/users/'+event.params.id+'/NotificationToken/IOS').once('v‌​alue').then((snapshot) => { 
var token=snapshot.val().IOS;

 });
Peter Haddad
  • 78,874
  • 25
  • 140
  • 134
  • I am getting this error: 24:1 error Expected catch() or return promise/catch-or-return – ajeet sharma Mar 12 '18 at 07:11
  • check this: https://stackoverflow.com/questions/48582278/eslint-error-trying-to-deploy-functions-firebase – Peter Haddad Mar 12 '18 at 07:20
  • Cloud function has deployed successfully but I am getting error in cloud function console. I edited my question please have a look. – ajeet sharma Mar 12 '18 at 07:39
  • @ajeetsharma use once() instead of on() and get the value once – Peter Haddad Mar 12 '18 at 07:41
  • it's not working :( . getting this error in console: TypeError: Cannot read property 'IOS' of null at admin.database.ref.once.then (/user_code/index.js:34:29) at process._tickDomainCallback (internal/process/next_tick.js:135:7) – ajeet sharma Mar 12 '18 at 08:57