Вопрос:

Cloud functions HTTPS trigger to generate unique user IDs

javascript firebase firebase-realtime-database google-cloud-functions app-inventor

670 просмотра

1 ответ

83 Репутация автора

For an AppInventor app which uses Firebase as database, I want to give unique user IDs to app users. After looking for some options I had the idea that I could use a Cloud HTTP function to be requested by the app, and the returning data would be a UserId generated by simply incrementing the last UserId in the UserIds table (not sure if it is one, either).

That's the story, but I can't make the following code to deploy (and when I can, it doesn't work as I expect). It reads the last UserId correctly, but I could only make it overwrite the previous data so far.

It throws an unexpected token error in the "." in 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});
});
Автор: Ugur Источник Размещён: 08.11.2017 11:30

Ответы (1)


1 плюс

4899 Репутация автора

Решение

The Firebase Authentication package provides an automatically generated unique ID for every authenticated user already, which you can obtain from firebase.auth().currentUser.uid on web and similar methods for other platforms.

If you still want to generate your own incremental ID using Cloud Functions, you'll need to make use of a transaction and then send back the new ID, something like:

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());
    });
});

This increments the lastUserId value in the database using a transaction and then sends this new ID back as a response (using res.send()) for use in the calling app.

Автор: Grimthorr Размещён: 09.11.2017 08:38
Вопросы из категории :
32x32