如何解决如何处理在回调之前运行的重复代码
我正在创建一个剩余的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 举报,一经查实,本站将立刻删除。