如何使用Firebase Cloud函数在内部生成随机ID?

时间:2019-06-24 09:04:48

标签: android firebase firebase-realtime-database google-cloud-functions

我想实现如下图所示:

enter image description here

当数据库中创建了新节点时,我想使用Firebase云功能生成此 SomeRandomId

我之前做过这样的事情,它会在otherdetails键值对上生成 randomIds ,效果很好,并且实现如下。

const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp(functions.config().firebase);


exports.addUniqueCode = 
functions.database.ref('/Users/{userId}/').onCreate((snapshot , 
                                        context ) => {
  const code = makeid(6);

  var userdata = snapshot.val();

  console.log(code);

  return snapshot.ref.update({ otherdetails : code});

});

function makeid(length) {
   var result           = '';
   var characters       = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
   var charactersLength = characters.length;
   for ( var i = 0; i < length; i++ ) {
   result += characters.charAt(Math.floor(Math.random() * 
                                     charactersLength));
   }
   return result;
}

//console.log(makeid(6));

0 个答案:

没有答案