有没有办法通过Firebase云功能在服务器端实例化新客户端?

时间:2019-09-04 06:14:56

标签: getstream-io

我正在开发一个应用,并尝试使用react native和firebase通过getstream.io实现新闻提要。 有没有一种方法可以使用Firebase Cloud函数生成用户令牌。如果有的话,请您指点一下我该怎么做? (云功能端和客户端的代码段将非常有帮助。) 我看到了类似的问题,只是没有找到具体的教程..任何帮助,感激不尽!

1 个答案:

答案 0 :(得分:1)

对于云功能端,您需要创建一个https.onRequest端点,该端点调用createUserToken如下:

const functions = require('firebase-functions');
const stream = require('getstream');

const client = stream.connect('YOUR_STREAM_KEY', 'YOUR_STREAM_SECRET', 'YOUR_STREAM_ID');

exports.getStreamToken = functions.https.onRequest((req, res) => {
    const token = client.createUserToken(req.body.userId);
    return { token };
});

然后,在终端中使用firebase deploy --only functions进行部署,并从您的Firebase仪表板获取该功能的网址。

然后,您可以在axios或fetch等类似的POST请求中使用该网址:

const { data } = axios({
    data: {
        userId: 'lukesmetham', // Pass the user id for the user you want to generate the token for here.
    },
    method: 'POST',
    url: 'CLOUD_FUNC_URL_HERE',
});

现在,data.token将是返回的流令牌,您可以将其保存到AsyncStorage或想要存储它的任何位置。您是将用户数据保留在firebase / firestore中还是将其自身流化?有了更多的背景知识,我可以根据您的设置为您添加以上代码!希望这会有所帮助!

更新:

const functions = require('firebase-functions');
const stream = require('getstream');

const client = stream.connect('YOUR_STREAM_KEY', 'YOUR_STREAM_SECRET', 'YOUR_STREAM_ID');

// The onCreate listener will listen to any NEW documents created
// in the user collection and will only run when it is created for the first time.

// We then use the {userId} wildcard (you can call this whatever you like.) Which will
// be filled with the document's key at runtime through the context object below.

exports.onCreateUser = functions.firestore.document('user/{userId}').onCreate((snapshot, context) => {
    // Snapshot is the newly created user data.
    const { avatar, email, name } = snapshot.val();
    const { userId } = context.params; // this is the wildcard from the document param above.

    // you can then pass this to the createUserToken function
    // and do whatever you like with it from here
    const streamToken = client.createUserToken(userId);
});

让我知道是否需要解决,这些文档对于该主题也很有帮助?

https://firebase.google.com/docs/functions/firestore-events