From 0cacb634140383f8ca7df3bc3a96dc27c1d64607 Mon Sep 17 00:00:00 2001 From: Raymond Li <34190736+raylfli@users.noreply.github.com> Date: Tue, 5 Apr 2022 18:30:51 -0400 Subject: [PATCH] Fix API calls for game --- client/src/actions/game.js | 52 +++++++++++-------- .../src/react-components/TypeGame/TypeGame.js | 10 ++-- models/game.js | 4 +- routes/game.js | 24 ++++----- 4 files changed, 50 insertions(+), 40 deletions(-) diff --git a/client/src/actions/game.js b/client/src/actions/game.js index 80ca15d..b19d911 100644 --- a/client/src/actions/game.js +++ b/client/src/actions/game.js @@ -4,7 +4,7 @@ const API_HOST = ENV.api_host; export async function getTopScores(n, setTopUsers) { try { - const scores = `${API_HOST}/api/game/highscores/${n}`; + const scores = `${API_HOST}/api/game/highscores?n=${n}`; // fetch(scores) // .then(res => { // if (res.status === 200) { @@ -24,10 +24,11 @@ export async function getTopScores(n, setTopUsers) { if (res.status !== 200) { return; } - const resJSON = await res.json() + const resJSON = await res.json(); + for (const user of resJSON) { - const userUrl = ``; // I'm not sure what top put this line + const userUrl = `${API_HOST}/api/users/${user.username}`; const res2 = await fetch(userUrl); if (res.status !== 200) { return; @@ -44,7 +45,8 @@ export async function getTopScores(n, setTopUsers) { } -export function getHighscore(setBest) { +export async function getHighscore(setBest) { + const score = `${API_HOST}/api/game/highscore/user`; fetch(score) .then(res => { @@ -55,7 +57,7 @@ export function getHighscore(setBest) { } }) .then(json => { - if (json == null){ + if (json === null){ setBest(0) } else { setBest(json.highScore) @@ -64,21 +66,29 @@ export function getHighscore(setBest) { .catch(error => {}); } -export function addScore(score) { - - const req = new Request( - `${API_HOST}/api/game/score`, - { - method: 'POST', - headers: { - Accept: 'application/json', - 'Content-Type': 'application/json'}, - body: JSON.stringify({ - score: score - }) - } - ); - fetch(req).catch(error => {}); +export async function addScore(score) { + console.log('trying') + try { + const req = new Request( + `${API_HOST}/api/game/score`, + { + method: 'POST', + headers: { + Accept: 'application/json', + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ + score: score + }) + } + ); + console.log(score); + const res = await fetch(req); + const resJSON = await res.json(); + console.log(resJSON); + } catch (error) { + console.log(error); + } } export function getInitialWords(setWords, setDifficulty) { @@ -150,4 +160,4 @@ export function getDifficulty(word, setDifficulty){ } }) .catch(error => {}); -} \ No newline at end of file +} diff --git a/client/src/react-components/TypeGame/TypeGame.js b/client/src/react-components/TypeGame/TypeGame.js index b87f78e..b9f78ad 100644 --- a/client/src/react-components/TypeGame/TypeGame.js +++ b/client/src/react-components/TypeGame/TypeGame.js @@ -114,6 +114,7 @@ function TypeGame(){ }else{ clearInterval(timer) setTime(0) + console.log(score); addScore(score) getTopScores(5, setTopUsers) const game = document.getElementById("game") @@ -173,13 +174,12 @@ function TypeGame(){ let count = 0 setLeaderboard(topUsers.map((user) => { count += 1 - console.log(user) - return(<> + return(
{count}
-
{user.user.userame}
-
{user.user.displayName}
+
{user.username}
+
{user.displayName}
{user.highScore}
- +
) })) } diff --git a/models/game.js b/models/game.js index a40c90a..bfac26e 100644 --- a/models/game.js +++ b/models/game.js @@ -3,8 +3,8 @@ const mongoose = require('mongoose'); const Game = mongoose.model('Game', { - user: { - type: mongoose.Schema.Types.ObjectId, + username: { + type: String, required: true, unique: true }, diff --git a/routes/game.js b/routes/game.js index 0cffad8..3abd3c7 100644 --- a/routes/game.js +++ b/routes/game.js @@ -29,10 +29,10 @@ router.post('/api/game/score', mongoChecker, authenticate, async (req, res) => { try { // add to high scores - let user = await Game.findOne({user: req.session.user}); + let user = await Game.findOne({username: req.session.username}); if (!user) { user = new Game({ - user: req.session.user, + username: req.session.username, timestamp: Date.now(), highScore: req.body.score }); @@ -44,13 +44,13 @@ router.post('/api/game/score', mongoChecker, authenticate, async (req, res) => { } // add to user capital - user = await User.findById(req.session.user); - user.paperTrade.capital += Number(req.body.score); - user.paperTrade.totalMoneyIn += Number(req.body.score); - const result = await user.save(); - res.send(); + const user2 = await User.findById(req.session.user); + user2.paperTrade.capital += Number(req.body.score); + user2.paperTrade.totalMoneyIn += Number(req.body.score); + const result = await user2.save(); + res.send(user); } catch (error) { - res.send(error) + console.log(error); if (isMongoError(error)) { res.status(500).send('Internal server error'); } else { @@ -61,7 +61,7 @@ router.post('/api/game/score', mongoChecker, authenticate, async (req, res) => { }); /** - * GET /api/game/highscores/:n + * GET /api/game/highscores?n=5 * * Retrieve up to n of the highest scores for the game. * @@ -71,9 +71,9 @@ router.post('/api/game/score', mongoChecker, authenticate, async (req, res) => { * * Returns: 200 on success and an array of up to n of the highest scores */ -router.get('/api/game/highscores/:n', mongoChecker, authenticate, async (req, res) => { +router.get('/api/game/highscores', mongoChecker, authenticate, async (req, res) => { try { - const scores = await Game.find().sort({highScore: -1}).limit(req.params.n); + const scores = await Game.find().sort({highScore: -1}).limit(req.query.n); if (!scores) { res.status(404).send('Resource not found'); } else { @@ -101,7 +101,7 @@ router.get('/api/game/highscores/:n', mongoChecker, authenticate, async (req, re */ router.get('/api/game/highscore/user', mongoChecker, authenticate, async (req, res) => { try { - const highScore = await Game.findOne({user: req.session.user}); + const highScore = await Game.findOne({username: req.session.user}); if (!highScore) { res.status(404).send('Resource not found'); } else {