personal_website/controllers/gameController.ts
2024-07-16 20:18:46 +02:00

112 lines
3.3 KiB
TypeScript

import { type Request, type Response } from "express";
import UserModel, { values } from '../models/userModel';
import MediaModel, { Table } from '../models/mediaModel';
export default {
list: function (req: Request, res: Response) {
MediaModel.find(Table.games)
.then(games => {
return res.json(games);
})
.catch(err => {
return res.status(500).json({
message: 'Error when getting games.',
error: err
});
});
},
create: async function (req: Request, res: Response) {
var gameCode = req.body.code;
const twitch_client_id = await UserModel.getValue(values.twitch_client_id);
const twitch_client_secret = await UserModel.getValue(values.twitch_client_secret);
if (!twitch_client_id || !twitch_client_secret) {
return res.status(500).json({ message: 'Error when creating game' });
}
try {
const gameFound = await MediaModel.findOne(Table.games, gameCode);
if (gameFound) {
return res.status(409).json({ message: 'Game already exists' });
}
const uri = "https://id.twitch.tv/oauth2/token?client_id=" + twitch_client_id + "&client_secret=" + twitch_client_secret + "&grant_type=client_credentials";
var response = await fetch(uri, { method: 'POST' });
const mData = await response.json();
const mheaders: HeadersInit = {
'Accept': 'application/json',
'Client-ID': twitch_client_id,
'Authorization': 'Bearer ' + mData.access_token
}
gameCode = parseInt(gameCode)
response = await fetch(
"https://api.igdb.com/v4/games",
{
method: 'POST',
headers: mheaders,
body: `fields name, first_release_date; where id = ${gameCode};`
}
)
const gameData = await response.json()
if (gameData.length == 0) {
return res.status(404).json({ message: 'wrong code' });
}
const date = new Date(gameData[0].first_release_date * 1000);
const options: Intl.DateTimeFormatOptions = { day: 'numeric', month: 'short', year: 'numeric' }
const dateStr = date.toLocaleDateString(undefined, options);
response = await fetch(
"https://api.igdb.com/v4/covers",
{
method: 'POST',
headers: mheaders,
body: `fields image_id; where game = ${gameCode};`
}
)
const coverData = await response.json()
const game = {
code: gameCode,
title: gameData[0].name,
released: dateStr,
webImg: `https://images.igdb.com/igdb/image/upload/t_cover_big/${coverData[0].image_id}.jpg`,
};
const savedGame = await MediaModel.save(Table.games, game.code, game.title, game.released, game.webImg);
return res.status(201).json(game);
} catch (error) {
return res.status(500).json({ message: 'Error when creating game', error: error });
}
},
remove: async function (req: Request, res: Response) {
const code = req.body.code;
try {
const movie = await MediaModel.findOneAndDelete(Table.games, code);
if (!movie) {
return res.status(404).json({ message: 'No such game' });
}
return res.status(204).json();
}
catch (err) {
return res.status(500).json({ message: 'Error when deleting the game.' });
}
}
};