Commit 04d5a096 authored by Matthieu - Greep's avatar Matthieu - Greep

Create setVote.js

parent 5f8fbf53
Pipeline #447 passed with stage
in 50 seconds
const path = require('path'),
scriptName = path.basename(__filename).replace(/\.js$/i,'');
/**
* @param {import('express').Express} app
* @param {import('mysql').Connection} sql
*/
module.exports = function(app, sql, tokenCheck, errorHandler) {
app.post('/'+scriptName, function(req, res) {
tokenCheck(req, res, sql, ()=>{
const mapId = req.query.map,
player = req.query.player,
vote = Number(req.query.vote);
if (!mapId) return errorHandler(res, 400, 'Missing map id');
if (!player) return errorHandler(res, 400, 'Missing player login');
if (!vote) return errorHandler(res, 400, 'Missing vote');
if (isNaN(vote)) return errorHandler(res, 400, 'Invalid vote');
if (vote < 0 || vote > 100) return errorHandler(res, 400, 'Vote must be between 0 and 100');
sql.query('SELECT * FROM votes WHERE map = ? AND player = ?', [mapId,player], (err, sqlRes)=>{
if (err) {
console.log(err);
errorHandler(res, 500, 'Internal server error');
} else {
if (sqlRes.length === 0) { // Create a new vote for this player
sql.query('INSERT INTO votes (map, player, vote, date) VALUES (?, ?, ?, ?)', [mapId, player, vote, new Date()], (err)=>{
if (err) {
console.error(err);
errorHandler(res, 500, 'Internal server error');
} else {
res.json({
mapUid: mapId,
player: player,
vote: vote,
date: new Date(),
type: "new"
});
}
});
} else { // Update the vote for this player
sql.query('UPDATE votes SET vote = ?, date = ? WHERE map = ? AND player = ?', [vote, new Date(), mapId, player], (err)=>{
if (err) {
console.error(err);
errorHandler(res, 500, 'Internal server error');
} else {
res.json({
mapUid: mapId,
player: player,
vote: vote,
date: new Date(),
type: "update"
});
}
});
}
}
});
});
});
};
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment