route for fetching finished games

This commit is contained in:
Nathaniel Tampus
2023-04-01 23:42:33 +08:00
parent 710955b741
commit 5088e25769
3 changed files with 38 additions and 12 deletions

View File

@@ -1,11 +1,35 @@
import type { Request, Response } from "express";
import { activeGames } from "../db/models/game.model.js";
import GameModel, { activeGames } from "../db/models/game.model.js";
import type { Game, User } from "@chessu/types";
import { nanoid } from "nanoid";
export const getActivePublicGames = async (req: Request, res: Response) => {
export const getGames = async (req: Request, res: Response) => {
try {
res.status(200).json(activeGames.filter((g) => !g.unlisted && !g.winner));
if (!req.query.id && !req.query.userid) {
// get all active games
res.status(200).json(activeGames.filter((g) => !g.unlisted && !g.winner));
return;
}
if (req.query.id) {
// get finished game by id
const game = await GameModel.findById(parseInt(req.query.id as string));
if (!game) {
res.status(404).end();
} else {
res.status(200).json(game);
}
} else if (req.query.userid) {
// get finished games by user id
const games = await GameModel.findByUserId(parseInt(req.query.userid as string));
if (!games) {
res.status(404).end();
} else {
res.status(200).json(games);
}
} else {
res.status(400).end();
}
} catch (err: unknown) {
console.log(err);
res.status(500).end();