import express from "express"; import { authenticationGuard } from "../middleware/Authority.js"; import { needDatabase } from "../middleware/Database.js"; import Match from "../schemas/Match.js"; import Sport from "../schemas/Sport.js"; import User from "../schemas/User.js"; const MatchController = express.Router(); MatchController.get("/search/:sport", needDatabase, async (req, res) => { try { let sport = Sport.findByName(req.params.sport); let query = Match.find({ sport: sport._id }); query.where("dateTime").gte(Date.now); // We don't want to return any results of matches that have already occurred. if (req.query.within) query.where("location").within({ center: req.query.location.split(","), radius: req.query.within }); if (req.query.minDifficulty) query.where("difficulty").gte(req.query.minDifficulty); if (req.query.maxDifficulty) query.where("difficulty").lte(req.query.maxDifficulty); if (req.query.beforeDate) query.where("dateTime").lte(req.query.beforeDate); let queryResults = await query; res.send({ queryResults }); } catch (error) { console.error(error); res.status(500).send("Internal server error."); } }); // TODO: delete, update match. MatchController.post("/", needDatabase, authenticationGuard, async (req, res) => { try { const userId = req.session.userId; const match = new Match({ title: req.body.title, dateTime: req.body.dateTime, public: req.body.public, location: req.body.location, creator: userId, difficulty: req.body.difficulty, sport: await Sport.findByName(req.body.sport) }); await match.save(); const user = await User.findById(userId); user.createdMatches.push(match._id); user.participatingMatches.value.push(match._id); await user.save(); res.status(201).send(match); } catch (error) { console.error(error); res.status(500).send("Internal server error."); // TODO: Develop the error handling. } }); MatchController.get("/:matchId", needDatabase, async (req, res) => { if (!req.params.matchId) { res.status(404).send("Id must be provided to retrieve match"); return; } try { const match = await Match.findById(req.params.matchId); if (match) { res.status(200).send(match); } else { res.status(404).send("Could not find match with ID: " + req.params.matchId); } } catch (error) { res.status(500).send("Internal server error."); // TODO: Develop the error handling. } }); export default MatchController;