112 lines
2.8 KiB
JavaScript
112 lines
2.8 KiB
JavaScript
const db = require("../models/index");
|
|
const BullpenSession = db.BullpenSession;
|
|
const Pitch = db.Pitch;
|
|
const Op = db.Sequelize.Op;
|
|
|
|
const getPagination = (page, size) => {
|
|
const limit = size ? +size : 3;
|
|
const offset = page ? page * limit : 0;
|
|
|
|
return { limit, offset };
|
|
};
|
|
|
|
const getPageData = (data, totalCount, page, limit) => {
|
|
const currentPage = page ? +page : 0;
|
|
const totalPages = Math.ceil(totalCount / limit);
|
|
|
|
return { totalCount, data, totalPages, currentPage };
|
|
};
|
|
|
|
exports.insert = (req, res) => {
|
|
BullpenSession.create(req.body, { include: [{
|
|
model: Pitch,
|
|
as: 'pitches'
|
|
}]}
|
|
)
|
|
.then(bullpenSession => {
|
|
return res.status(201).send(bullpenSession);
|
|
})
|
|
.catch(err => {
|
|
res.status(500).send({ message: err.message });
|
|
});
|
|
};
|
|
|
|
exports.findAll = (req, res) => {
|
|
const { page, size, user } = req.query;
|
|
const condition = user ? { pitcherId: { [Op.eq]: parseInt(user, 10) } } : null;
|
|
|
|
const { limit, offset } = getPagination(page, size);
|
|
|
|
let totalCount = 0;
|
|
BullpenSession.count({
|
|
where: condition,
|
|
limit,
|
|
offset
|
|
}).then(count => {
|
|
totalCount = count;
|
|
return BullpenSession.findAll({
|
|
where: condition,
|
|
limit,
|
|
offset,
|
|
include: {
|
|
model: Pitch,
|
|
as: 'pitches'
|
|
}
|
|
});
|
|
})
|
|
.then(bullpenSessions => {
|
|
const response = getPageData(bullpenSessions, totalCount, page, limit);
|
|
res.status(200).send(response);
|
|
});
|
|
}
|
|
|
|
exports.findOne = (req, res) => {
|
|
const id = req.params.id;
|
|
BullpenSession.findByPk(id, {
|
|
include: {
|
|
model: Pitch,
|
|
as: 'pitches'
|
|
}
|
|
})
|
|
.then(data => {
|
|
if (data) {
|
|
res.send(data);
|
|
} else {
|
|
res.status(404).send({
|
|
message: `Cannot find bullpen session with id=${id}.`
|
|
});
|
|
}
|
|
})
|
|
.catch(err => {
|
|
res.status(500).send({
|
|
message: `Error retrieving bullpen session with id=${id}: ${err.message}`
|
|
});
|
|
});
|
|
}
|
|
|
|
exports.summaryForPlayer = (req, res) => {
|
|
const { user } = req.query;
|
|
const condition = user ? { pitcherId: { [Op.eq]: parseInt(user, 10) } } : null;
|
|
|
|
BullpenSession.findAll({
|
|
where: condition,
|
|
include: {
|
|
model: Pitch,
|
|
as: 'pitches'
|
|
}
|
|
}).then(data => {
|
|
const summary = {
|
|
pitchCount: 0,
|
|
precisionRate: 0,
|
|
strikeRate: 0,
|
|
ballRate: 0,
|
|
since: new Date()
|
|
};
|
|
|
|
}).catch(err => {
|
|
res.status(500).send({
|
|
message: `Error retrieving bullpens for user with id=${user}: ${err.message}`
|
|
});
|
|
});
|
|
}
|