如何在Firebase云功能之间传递数据

时间:2019-01-06 08:45:19

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

我正在尝试通过发出https请求来从客户端应用调用函数来从应用中获取当前用户ID。它正在工作,我正在获取uid。问题是无论何时触发onWrite()函数,我都需要在特定用户ID下向特定用户发送通知。如何将从https函数获得的uid传递给触发函数?

我刚刚使用https.onCall()从客户端应用程序检索了当前用户的用户ID。 然后在触发功能中,我尝试使用expo push notifications API将通知发送给按uid分类的特定用户。

functions / index.js

const functions = require('firebase-functions');
var fetch = require('node-fetch')

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


exports.getUid = functions.https.onCall((data, context) => {
    uid = data.text
    console.log(data.text)
})

exports.makerOrders = functions.database.ref('orders')
    .onWrite((snapShot, context) => {
        console.log('functions is triggered :)')

    return admin.database().ref('Notifications').child(uid)
        .once('value')
        .then((shot) => {
            var message = []

            var tokens = shot.val().expoTokens;

            if (tokens) {
                message.push({
                    "to": tokens,
                    "body": "Notifications are working fine :)"
                })
            }
            return Promise.all(message)
        }).then(message => {
            fetch('http://exp.host/--/api/v2/push/send', {
                method: "POST",
                headers: {
                    "Accept": "application/json",
                    "Content-Type": "application/json"
                },
                body: JSON.stringify(message)
            })
            return Promise.all(message)
        })
})

App.js

var uid = firebase.auth().currentUser.uid
var getUid = firebase.functions().httpsCallable('getUid')
getUid({text: uid}).then(result => {
  var msg = result.data
  console.log(msg)
  console.log('Called successfully :)')
}).catch(error => {
  console.log('Error :( in sending the requests')
});

我希望从应用程序中获取当前用户的uid值,以便我可以向该特定用户发送推送通知。

我无法检索当前已认证用户的uid。

1 个答案:

答案 0 :(得分:0)

In order to pass data between functions there are two ways of doing this. You can use a function that it is triggered by HTTP request or a function that is triggered by Pub/Sub topic.

HTTP:

  1. Create a Cloud Function with HTTP trigger
  2. Open the details of the created function and under the Trigger tab you will find the URL that triggers the function. Use that URL to parse data from another function.
  3. In the other function run a request using that URL and add at the end '?data=DATA_T0_SEND'
  4. Catch the data from the second function using return request.args.get('data')

Pub/Sub:

  1. Create a Cloud Function that triggers by a Pub/Sub topic.
  2. On the other function use the Pub/Sub library to send the data to the topic
  3. When the functions will be triggered with the Pub/Sub event get the data
  4. Now process the data from that event