So the situation is as fallow:
I need to search in 3 different db for a id of a shift. But the shift has also a type: Activity, Food And Beverages or other.
The way i do it, in my req.body I also have a type.
So i use a switch statement to determine which db i need to search through
switch(type_shift){
case("activity"):
response = await ActivityShiftDB.findByIdAndUpdate(id_shift, {$pull : {"support": user}}).exec();
break;
case("fandb"):
response = await FoodBeveragesShiftDB.findByIdAndUpdate(id_shift, {$pull : {"support": user}}).exec();
break;
case("other"):
response = await OtherShiftDB.findByIdAndUpdate(id_shift, {$pull : {"support": user}}).exec();
break;
}
This code doesn't feel DRY, Is there an other way to do this?
Put the shared part after the switch
statement:
let shiftDB;
switch (type_shift) {
case "activity":
shiftDB = ActivityShiftDB;
break;
case "fandb":
shiftDB = FoodBeveragesShiftDB;
break;
case "other":
shiftDB = OtherShiftDB;
break;
default:
throw new Error("unknown type_shift");
}
response = await shiftDB.findByIdAndUpdate(id_shift, {$pull : {"support": user}}).exec();
Then, simplify by not using a switch
statement:
const shiftDBsByType = {
"activity": ActivityShiftDB,
"fandb": FoodBeveragesShiftDB,
"other": OtherShiftDB,
}
if (!(type_shift in shiftDBsByType)) {
throw new Error("unknown type_shift");
}
response = await shiftDBsByType[type_shift].findByIdAndUpdate(id_shift, {$pull : {"support": user}}).exec();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.