sports-matcher/server/controllers/matchController.js

72 lines
2.8 KiB
JavaScript
Raw Normal View History

import express from "express";
import { authenticationGuard } from "../middleware/authority.js";
import { needDatabase } from "../middleware/database.js";
import matchModel from "../schemas/matchModel.js";
import sportModel from "../schemas/sportModel.js";
import userModel from "../schemas/userModel.js";
const MatchController = express.Router();
MatchController.get("/search/:sport", needDatabase, async (req, res) => {
try {
let sport = sportModel.findByName(req.params.sport);
let query = matchModel.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 user = await userModel.findById(userId);
const match = new matchModel({
title: req.body.title,
dateTime: req.body.dateTime,
public: req.body.public,
location: req.body.location,
creator: userId,
difficulty: req.body.difficulty,
sport: await sportModel.findByName(req.body.sport),
participants: [user._id]
});
await match.save();
user.createdMatches.push(match._id);
user.participatingMatches.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 matchModel.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;