Files
17th-Battalion-Tracker/api/db/controllers/Award.controller.js
IndigoFox 9f2473801c Initial commit
TODO: change api.conf URL references to use environment variables and add these variables to the docker-compose configuration for host domain
2023-03-28 00:08:50 -07:00

71 lines
1.6 KiB
JavaScript

const db = require("..");
const Award = db.Award;
const Op = db.Sequelize.Op;
// Create and Save a new Award
exports.create = (req, res) => {
// Validate
if (!req.body) {
res.status(400).send({
message: "Body content can not be empty!"
});
return;
}
const awards = []
if (Array.isArray(req.body)) {
awards.push(...req.body)
} else {
awards.push(req.body)
}
// Save
const promises = awards.map(award => {
return Award.create(award)
});
// Create
const successes = []
const failures = []
Promise.allSettled(promises)
.then(data => {
if (data.every(result => result.status === 'fulfilled')) {
res.status(201).send({
message: "All awards were created successfully.",
successes: data.map(result => result.value),
failures: [],
})
return;
}
data.forEach(result => {
if (result.status === 'fulfilled') {
successes.push(result.value)
} else {
failures.push(result.reason.errors)
}
})
if (successes.length === 0) {
res.status(500).send({
message:
"Failed to create any Awards.",
failures: failures,
successes: successes,
});
return;
}
res.status(207).send({
message: "Some Awards were created successfully.",
successes: successes,
failures: failures,
})
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while creating the Award.",
});
});
};