【问题标题】:Cloud functions HTTPS trigger to generate unique user IDs云函数 HTTPS 触发器以生成唯一的用户 ID
【发布时间】:2017-11-08 23:30:48
【问题描述】:

对于使用 Firebase 作为数据库的 AppInventor 应用,我想为应用用户提供唯一的用户 ID。在寻找了一些选项后,我想到我可以使用应用程序请求的 Cloud HTTP 函数,返回的数据将是通过简单地递增 UserIds 表中的最后一个 UserId 生成的 UserId(也不确定是不是一个)。

故事就是这样,但我无法制作以下代码来部署(如果可以,它不会像我预期的那样工作)。它正确读取了最后一个UserId,但我只能让它覆盖之前的数据。

它会在functions.https 中的"." 中引发意外令牌错误。

const functions = require('firebase-functions');
// Import and initialize the Firebase Admin SDK.
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

var LastUserId = function f() {return admin.database().ref('UserIds').limitToLast(1)}

exports.addWelcomeMessages = functions.https.onRequest((request, response)) => {
    var ref = admin.database().ref('UserIds');
    // this new, empty ref only exists locally
    var newChildRef = ref.push();
    // we can get its id using key()
    console.log('my new shiny id is '+newChildRef.key());
    // now it is appended at the end of data at the server
    newChildRef.set({User : LastUserId + 1});
});

【问题讨论】:

    标签: javascript firebase firebase-realtime-database google-cloud-functions app-inventor


    【解决方案1】:

    Firebase 身份验证包已经为每个经过身份验证的用户提供了一个自动生成的唯一 ID,您可以从网络上的 firebase.auth().currentUser.uid 和其他平台的类似方法中获取该 ID。

    如果您仍想使用 Cloud Functions 生成自己的增量 ID,则需要使用 transaction,然后发回新 ID,例如:

    const functions = require('firebase-functions');
    const admin = require('firebase-admin');
    admin.initializeApp(functions.config().firebase);
    
    exports.generateUserId = functions.https.onRequest((req, res) => {
        var ref = admin.database().ref('/lastUserId');
        ref.transaction(function(current) {
          return (current || 0) + 1;
        }, function(error, committed, snapshot) {
          if (error || !committed || !snapshot) {
            console.error("Transaction failed abnormally!", error || "");
          } else {
            console.log("Generated ID: ", snapshot.val());
          }
          res.status(200).send(snapshot.val().toString());
        });
    });
    

    这会使用事务增加数据库中的 lastUserId 值,然后将此新 ID 作为响应(使用 res.send())发回以供调用应用程序使用。

    【讨论】:

    • 这是否写入数据库以及我在这里尝试执行的操作:newChildRef.set({User : LastUserId + 1});
    • 是的,事务会将返回的任何值写回同一位置,因此return (current || 0) + 1; 会将当前值加 1(如果 lastUserId 不存在,则从 0 开始)和然后自动保存回数据库。
    • 数据库写入正常,但我在日志中收到错误,它没有返回写入的数据:TypeError: Cannot read property 'val' of undefined at admin.database.ref.transaction.then (/user_code/index.js:15:38) at process._tickDomainCallback (internal/process/next_tick.js:135:7) 有什么想法吗?
    • 糟糕,对不起,这是我的错,我实际上并没有测试代码!查看我已重新编写和测试的更新代码。
    • 您还可以考虑使用 GUID / UUID - 它们在插入时间之前创建它们方面有一些好处。你可以在这里阅读更多关于它的信息stackoverflow.com/questions/45399/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-31
    • 2010-09-11
    • 2018-04-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多