Skip to content

Commit

Permalink
Fix API calls for game
Browse files Browse the repository at this point in the history
  • Loading branch information
raylfli committed Apr 5, 2022
1 parent 85b0fd2 commit 0cacb63
Show file tree
Hide file tree
Showing 4 changed files with 50 additions and 40 deletions.
52 changes: 31 additions & 21 deletions client/src/actions/game.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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;
Expand All @@ -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 => {
Expand All @@ -55,7 +57,7 @@ export function getHighscore(setBest) {
}
})
.then(json => {
if (json == null){
if (json === null){
setBest(0)
} else {
setBest(json.highScore)
Expand All @@ -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) {
Expand Down Expand Up @@ -150,4 +160,4 @@ export function getDifficulty(word, setDifficulty){
}
})
.catch(error => {});
}
}
10 changes: 5 additions & 5 deletions client/src/react-components/TypeGame/TypeGame.js
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ function TypeGame(){
}else{
clearInterval(timer)
setTime(0)
console.log(score);
addScore(score)
getTopScores(5, setTopUsers)
const game = document.getElementById("game")
Expand Down Expand Up @@ -173,13 +174,12 @@ function TypeGame(){
let count = 0
setLeaderboard(topUsers.map((user) => {
count += 1
console.log(user)
return(<>
return(<div key={ uid(user) }>
<div className='grid-item-bold'>{count}</div>
<div className='grid-item-bold'>{user.user.userame}</div>
<div className='grid-item-bold'>{user.user.displayName}</div>
<div className='grid-item-bold'>{user.username}</div>
<div className='grid-item-bold'>{user.displayName}</div>
<div className='grid-item-bold'>{user.highScore}</div>
</>
</div>
)
}))
}
Expand Down
4 changes: 2 additions & 2 deletions models/game.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
},
Expand Down
24 changes: 12 additions & 12 deletions routes/game.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
});
Expand All @@ -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 {
Expand All @@ -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.
*
Expand All @@ -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 {
Expand Down Expand Up @@ -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 {
Expand Down

0 comments on commit 0cacb63

Please sign in to comment.