【问题标题】:Is there a way to instantiate a new client on server side by firebase cloud function?有没有办法通过firebase云功能在服务器端实例化一个新客户端?
【发布时间】:2019-09-10 15:47:19
【问题描述】:

我正在开发一个应用程序并尝试通过 getstream.io 使用 react native 和 firebase 实现新闻提要。 有没有办法通过使用 firebase 云功能生成用户令牌。如果有,请您给我一个指示,我该怎么做? (云功能端和客户端的代码sn-p会非常有帮助..) 我见过类似的问题,只是发现没有具体的教程..任何帮助表示赞赏!

【问题讨论】:

    标签: getstream-io


    【解决方案1】:

    对于云功能端,您需要创建一个调用createUserTokenhttps.onRequest 端点,如下所示:

    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 仪表板获取函数的 url。

    然后您可以在 POST 请求中使用 axios 或 fetch 或类似的 url:

    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

    【讨论】:

    • 谢谢卢克!它奏效了 :) 我会将我的用户数据保存在 firebase/firestore 中。
    • 太棒了!因此,如果您将数据存储在 Firestore 中,您可以在云函数中使用 onCreate 侦听器。我会为你稍微更新我的答案?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 2020-07-12
    • 2017-08-31
    • 1970-01-01
    • 2014-03-15
    • 2010-10-07
    • 2011-10-01
    相关资源
    最近更新 更多