Firebase的订单Id生成算法

Firebase的订单Id生成算法,firebase,random,uniqueidentifier,Firebase,Random,Uniqueidentifier,我希望firebase上使用云函数生成的订单/发票具有唯一且可读的id。 我认为基于uid和时间戳的随机id是一个很好的解决方案,因为用户不能同时发送两个订单 你觉得怎么样 我已经编辑了这个要点=> 结果如下: export default (() => { const PUSH_CHARS = '0123456789abcdefghijklmnopqrstuvwxyz'; let lastPushTime = 0; let lastRandChars = []; re

我希望firebase上使用云函数生成的订单/发票具有唯一且可读的id。 我认为基于uid和时间戳的随机id是一个很好的解决方案,因为用户不能同时发送两个订单

你觉得怎么样

我已经编辑了这个要点=>

结果如下:

export default (() => {
  const PUSH_CHARS = '0123456789abcdefghijklmnopqrstuvwxyz';

  let lastPushTime = 0;
  let lastRandChars = [];

  return (uid) => {
    if (uid.length != 28) throw new Error('UID length should be 28.');

    let now = new Date().getTime();
    const duplicateTime = (now === lastPushTime);
    lastPushTime = now;

    // CONVERT TimeStamp to CHARS
    const timeStampChars = new Array(8);
    let i;
    for (i = timeStampChars.length - 1; i >= 0; i--) {
      timeStampChars[i] = PUSH_CHARS.charAt(now % 36);

      now = Math.floor(now / 36);
    }
    if (now !== 0) throw new Error('We should have converted the entire timestamp.');

    let id = timeStampChars.join('');

    // ADD 2 random CHARS
    for (i = 0; i < 2; i++) {
      id += PUSH_CHARS.charAt(Math.floor(Math.random() * 36)).toLowerCase();
    }
    Math.max

    // ADD random chars of UID
    if (!duplicateTime) {
      for (i = 0; i < 6; i++) {
        lastRandChars[i] = Math.floor(Math.random() * 28);
      }
    } else {
      for (i = 5; i >= 0 && lastRandChars[i] === 27; i--) {
        lastRandChars[i] = 0;
      }
      lastRandChars[i]++;
    }
    for (i = 0; i < 6; i++) {
      id += uid.charAt(lastRandChars[i]).toLowerCase();
    }

    // The id must be 16
    if (id.length != 16) throw new Error('Length should be 16.');

    return id;
  };
})();
导出默认值(()=>{
常量PUSH_CHARS='0123456789abcdefghijklmnopqrstuvwxyz';
设lastPushTime=0;
设lastRandChars=[];
返回(uid)=>{
如果(uid.length!=28)抛出新错误('uid length应该是28');
现在让我们=new Date().getTime();
const duplicateTime=(now==lastPushTime);
lastPushTime=现在;
//将时间戳转换为字符
const timeStampChars=新数组(8);
让我;
对于(i=timeStampChars.length-1;i>=0;i--){
timeStampChars[i]=PUSH_CHARS.charAt(现在是%36);
now=数学楼层(now/36);
}
如果(现在!==0)抛出新错误('我们应该转换整个时间戳');
设id=timeStampChars.join(“”);
//添加2个随机字符
对于(i=0;i<2;i++){
id+=PUSH_CHARS.charAt(Math.floor(Math.random()*36)).toLowerCase();
}
马克斯
//添加UID的随机字符
如果(!重复时间){
对于(i=0;i<6;i++){
lastRandChars[i]=Math.floor(Math.random()*28);
}
}否则{
对于(i=5;i>=0&&lastRandChars[i]==27;i--){
lastRandChars[i]=0;
}
lastRandChars[i]++;
}
对于(i=0;i<6;i++){
id+=uid.charAt(lastRandChars[i]).toLowerCase();
}
//id必须是16
如果(id.length!=16)抛出新错误('长度应为16');
返回id;
};
})();

好主意,但你可以用简单的方法来做

生成唯一id

let key = databaseReference.push().getKey();
禁止用户仅在1分钟后添加订单

$order": {
    ".write": "data.child('timestamp').val() > (now - 60000)",
}

是的,但是firebase生成一个密钥,如下=>'-JRHTHaIs jNPLXOQivY',但是我想要一个更可读的id,如下=>'j4jo-f9v2-l6v8-srpv',您可以使用nodejs
uuid
lib,它生成一个好的可读uuid