Add winners manually by posting /lottery/winners.

This commit is contained in:
2021-01-24 15:34:58 +01:00
parent 2f3a6aeba7
commit b5b61784cc
2 changed files with 72 additions and 2 deletions

View File

@@ -1,8 +1,62 @@
const path = require("path");
const lotteryRepository = require(path.join(__dirname, "../lottery"));
const addWinners = (req, res) => {
const { winners } = req.body;
if (!(winners instanceof Array)) {
return res.status(400).send({
message: "Winners must be array.",
success: false
});
}
const requiredAttributes = ["name", "color"];
const validColors = ["red", "blue", "green", "yellow"];
const validateAllWinners = winners =>
winners.map(winner => {
return Promise.all(
requiredAttributes.map(attr => {
if (typeof winner[attr] === "undefined") {
return Promise.reject({
message: `Incorrect or missing attribute: ${attr}.`,
statusCode: 400
});
}
if (!validColors.includes(winner.color)) {
return Promise.reject({
message: `Missing or incorrect color value, must have one of values: ${validColors.join(", ")}.`,
statusCode: 400
});
}
return Promise.resolve();
})
).then(_ => Promise.resolve(winner));
});
return Promise.all(validateAllWinners(winners))
.then(winners => lotteryRepository.addWinners(winners))
.then(winners =>
res.send({
winners: winners,
message: `Successfully added winners to lottery.`,
success: true
})
)
.catch(error => {
const { statusCode, message } = error;
return res.status(statusCode || 500).send({
message: message || "Unexpected error occured adding winners.",
success: false
});
});
};
const allWinners = (req, res) => {
const isAdmin = req.isAuthenticated() || true;
const isAdmin = req.isAuthenticated();
return lotteryRepository
.allWinners(isAdmin)
@@ -94,6 +148,7 @@ const deleteWinners = (req, res) => {
};
module.exports = {
addWinners,
allWinners,
winnerById,
deleteWinnerById,

View File

@@ -189,7 +189,21 @@ const deleteWines = () => {
return PreLotteryWine.deleteMany();
};
const allWinners = isAdmin => {
const addWinners = winners => {
return Promise.all(
winners.map(winner => {
let newWinnerElement = new VirtualWinner({
name: winner.name,
color: winner.color,
timestamp_drawn: new Date().getTime()
});
return newWinnerElement.save();
})
);
};
const allWinners = (isAdmin = false) => {
if (!isAdmin) {
return VirtualWinner.find().then(winners => winners.map(redactWinnerInfoMapper));
} else {
@@ -360,6 +374,7 @@ module.exports = {
updateWineById,
deleteWineById,
deleteWines,
addWinners,
allWinners,
winnerById,
deleteWinnerById,