asura-tmdb/src/server/index.js

76 lines
2.3 KiB
JavaScript
Raw Normal View History

2022-03-15 14:46:24 +01:00
const path = require("path");
const express = require("express");
2022-03-16 14:33:07 +01:00
require("dotenv").config();
2022-03-15 14:46:24 +01:00
2022-03-20 15:34:13 +01:00
// Our self-written module for handling database operations
let tmdb = require("./tmdb.js");
2022-03-15 14:46:24 +01:00
2022-03-20 15:34:13 +01:00
// #region Express setup
2022-03-16 14:33:07 +01:00
const app = express();
const port = 3000;
2022-03-20 15:34:13 +01:00
//app.engine('html', require('ejs').renderFile);
2022-03-15 14:46:24 +01:00
app.listen(port, () => {
console.log(`Listening on port ${port}`)
})
2022-03-20 21:06:35 +01:00
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
2022-03-20 15:34:13 +01:00
// #endregion
2022-03-15 14:46:24 +01:00
2022-03-20 15:34:13 +01:00
// #region frontend
// Serve static files from the React app
2022-03-15 14:46:24 +01:00
app.get("/", (req, res) => {
2022-03-16 14:33:07 +01:00
res.sendFile(path.join(__dirname, "public", "landing.html"));
});
2022-03-20 15:34:13 +01:00
// #endregion
// #region API
app.get("/tournament/getTournaments", (req, res) => {
tmdb.getTournaments()
.then(tournaments => {res.json({"status": "OK", "data": tournaments}); })
.catch(err => {res.json({"status": "error", "data": err}); });
});
2022-03-16 14:33:07 +01:00
2022-03-16 15:40:33 +01:00
app.get("/tournament/:tournamentId/getMatches", (req, res) => {
let tournamentId = req.params.tournamentId;
if (isNaN(tournamentId)) {
res.json({"status": "error", "data": "tournamentId must be a number"});
return
}
tournamentId = parseInt(tournamentId);
2022-03-20 15:34:13 +01:00
tmdb.getMatchesByTournamentId(tournamentId)
.then(matches => res.send({"status": "OK", "data": matches}))
.catch(err => res.send({"status": "error", "data": err}));
2022-03-15 14:46:24 +01:00
});
2022-03-20 21:06:35 +01:00
app.get("/match/:matchId/getMatch", (req, res) => {
let matchId = req.params.matchId;
if (isNaN(matchId)) {
res.json({"status": "error", "data": "matchId must be a number"});
return
}
matchId = parseInt(matchId);
tmdb.getMatch(matchId)
.then(match => res.send({"status": "OK", "data": match}))
.catch(err => res.send({"status": "error", "data": err}));
});
// JSON body: {"winner": "teamId"}
app.post("/match/:matchId/setWinner", (req, res) => {
let matchId = req.params.matchId;
let winnerId = req.body.winnerId;
if (isNaN(matchId)) {
res.json({"status": "error", "data": "matchId must be a number"});
return
}
if (winnerId == undefined || isNaN(winnerId)) {
res.json({"status": "error", "data": "winnerId must be a number"});
return
}
matchId = parseInt(matchId);
winnerId = parseInt(winnerId);
tmdb.setMatchWinner(matchId, winnerId)
.then(match => res.send({"status": "OK", "data": match}))
.catch(err => res.send({"status": "error", "data": err}));
});
2022-03-20 15:34:13 +01:00
// #endregion