如何处理在回调之前运行的重复代码

问题描述

我正在创建一个剩余的POST端点,该端点将返回到GET端点的重定向,以详细了解通过POST请求为硬币创建的数据库条目。

为此,我生成一个随机ID,请调用db find来查看ID是否已存在。查找到的回调显示该ID是否已存在。

当前,这仅在ID不存在时有效,因为我可以创建记录并返回重定向

我不确定,是重复生成新的随机ID并在数据库中重复查找的正确方法。理想情况下,能够轻松设置最大尝试次数,然后返回http状态代码以供以后尝试。

这是我目前描述的代码

/** The /coins POST endpoint allows you to request a new coin be created,the value of the coin will be returned */
app.post('/coins',(req,res) => {
  console.log('Got a POST on /coins');
  // Generate a random 6 digit hex
  let coinID = Math.floor(Math.random()*16777215).toString(16).toupperCase();

  // Preform a find to check if ID already in use
  coinsDatabase.find({coin: coinID},(err,docs) => {
    if(err){
      console.log(err);
      return res.sendStatus(500);
    }

    // Check if any docs returned
    if(docs.length == 0){
      // The ID is not in use,use insert to make the record for a reserved coin ID
      coinsDatabase.insert({ coin: coinID,reserved: Date.Now()},newDoc) => {
        if(err){
          console.log(err);
          return res.sendStatus(500);
        }

        // Check if the record was successfully created
        if(newDoc !== undefined){
          // We have a entry,use it to request a forward to to correct get address
          res.header('Accept','application/json');
          res.redirect(303,`/coins/${coinID}`);
        }
        else{
          // The adding of a record Failed
          res.sendStatus(500);
        }
      });
    }
    else{
      // This ID was already in use,generate a new ID and recheck the db
      // Todo *************
    }
  });
});

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)