92 lines
2.4 KiB
JavaScript
92 lines
2.4 KiB
JavaScript
const db = require("../models/index");
|
|
const Team = db.Team;
|
|
const Player = db.Player;
|
|
const Op = db.Sequelize.Op;
|
|
|
|
exports.insert = (req, res) => {
|
|
Team.create(req.body)
|
|
.then(team => {
|
|
return res.status(201).send(team);
|
|
})
|
|
.catch(err => {
|
|
res.status(500).send({ message: err.message });
|
|
});
|
|
}
|
|
|
|
exports.findAll = (req, res) => {
|
|
const title = req.query.title;
|
|
const condition = title ? {title: {[Op.iLike]: `%${title}%`}} : null;
|
|
|
|
Team.findAll({
|
|
where: condition,
|
|
include: ['players']
|
|
}).then(data => {
|
|
res.send(data);
|
|
}).catch(err => {
|
|
res.status(500).send({
|
|
message:
|
|
err.message || "Some error occurred while retrieving teams."
|
|
});
|
|
});
|
|
};
|
|
|
|
exports.findOne = (req, res) => {
|
|
const id = req.params.id;
|
|
|
|
Team.findByPk(id, {
|
|
include: ['players']
|
|
}).then(data => {
|
|
res.send(data);
|
|
}).catch(err => {
|
|
res.status(500).send({
|
|
message: `Error retrieving team with id=${id}: ${err.message}`
|
|
});
|
|
});
|
|
};
|
|
|
|
exports.addPlayer = async (req, res) => {
|
|
const teamId = req.params.id;
|
|
const { playerIds } = req.body;
|
|
|
|
try {
|
|
// Fetch the team by ID
|
|
const team = await Team.findByPk(teamId);
|
|
|
|
if (!team) {
|
|
return res.status(404).send({ message: `Team with id=${teamId} not found.` });
|
|
}
|
|
|
|
// Add multiple players to the team
|
|
await team.addPlayers(playerIds);
|
|
|
|
res.status(200).send({ message: `Players added to team with id=${teamId} successfully.` });
|
|
} catch (err) {
|
|
res.status(500).send({
|
|
message: `Error adding players to team with id=${teamId}: ${err.message}`
|
|
});
|
|
}
|
|
}
|
|
|
|
exports.removePlayer = async (req, res) => {
|
|
const teamId = req.params.id;
|
|
const { playerIds } = req.body;
|
|
|
|
try {
|
|
// Fetch the team by ID
|
|
const team = await Team.findByPk(teamId);
|
|
|
|
if (!team) {
|
|
return res.status(404).send({ message: `Team with id=${teamId} not found.` });
|
|
}
|
|
|
|
// Add multiple players to the team
|
|
await team.removePlayers(playerIds);
|
|
|
|
res.status(200).send({ message: `Players added to team with id=${teamId} successfully.` });
|
|
} catch (err) {
|
|
res.status(500).send({
|
|
message: `Error adding players to team with id=${teamId}: ${err.message}`
|
|
});
|
|
}
|
|
}
|