personal_website/controllers/gameController.js
2023-08-02 21:35:06 +02:00

120 lines
3.3 KiB
JavaScript

var UserModel = require('../models/userModel');
var GameModel = require('../models/gameModel');
module.exports = {
list: function (req, res) {
GameModel.find({}, { _id: 0, __v: 0 })
.then(games => {
return res.json(games);
})
.catch(err => {
return res.status(500).json({
message: 'Error when getting games.',
error: err
});
});
},
create: async function (req, res) {
var gameCode = req.body.code;
const passp = req.body.pass;
try {
const userFound = await UserModel.findOne({ pass: passp });
if (!userFound) {
return res.status(404).json({ message: 'Wrong password' });
}
const gameFound = await GameModel.findOne({ code: gameCode });
if (gameFound) {
return res.status(409).json({ message: 'Game already exists' });
}
const uri = "https://id.twitch.tv/oauth2/token?client_id=" +userFound.client_id+ "&client_secret=" + userFound.client_secret+ "&grant_type=client_credentials";
var response = await fetch(uri, { method: 'POST' });
var mData = await response.json();
var mheaders = {
'Accept': 'application/json',
'Client-ID': userFound.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' });
}
var date = new Date(gameData[0].first_release_date * 1000);
const options = { day: 'numeric', month: 'short', year: 'numeric' }
var 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 = new GameModel({
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 game.save();
return res.status(201).json(game);
} catch (error) {
return res.status(500).json({ message: 'Error when creating game', error: error });
}
},
remove: async function (req, res) {
var id = req.body.code;
const passp = req.body.pass;
try {
const userFound = await UserModel.findOne({ pass: passp });
if (!userFound) {
return res.status(404).json({ message: 'Wrong password' });
}
const movie = await GameModel.findOneAndDelete({ code: id });
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.' });
}
}
};