javascript - Getting id of the current user from Cloud Functions and Firebase -
i using google cloud functions register push notifications through firebase. in app, have notifications reference changes current user whenever new follower or like, etc. of right able send notification phone whenever whole reference child changes
for example, if single post liked, send notification. need observe current user send notification single person.
here javascript file
const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeapp(functions.config().firebase); exports.sendpushnotification = functions.database.ref('/notification/{id}').onwrite(event => { const payload = { notification: { title: 'new message arrived', body: 'come check it', badge: '1', sound: 'default', } }; return admin.database().ref('fcmtoken').once('value').then(alltoken => { if (alltoken.val()) { const token = object.keys(alltoken.val()); return admin.messaging().sendtodevice(token, payload).then(response => { }); } }); });
i replace line:
functions.database.ref('/notification/{id}').onwrite(event => {
with this:
functions.database.ref('/notification/{id}').(the current user id).onwrite(event => {
how current users id?
you seem new javascript (calling json sort-of give-away that). cloud functions firebase not best way learn javascript. recommend first reading firebase documentation web developers and/or taking firebase codelab web developer. cover many basic javascript, web , firebase interactions. after you'll better equipped write code cloud functions too.
now question: there no concept of "current user" in cloud functions. javascript code runs on server, , users can trigger code writing database.
you can figure out user triggered function, isn't want here. user triggered notification not 1 needs receive message. want instead read user target of notification.
one way read database path triggered function. if keep notifications per user in database this:
user_notifications $uid notification1: ... notification2: ...
you can trigger cloud function this:
exports.sendpushnotification = functions.database.ref('/user_notification/{uid}/{id}').onwrite(event => {
and in code of function, uid of user with:
var uid = event.params.uid;
Comments
Post a Comment