Skip to content

Commit

Permalink
Added enpoint functionalities to return the ranking position of each …
Browse files Browse the repository at this point in the history
…user
  • Loading branch information
Mister-Mario committed Apr 20, 2024
1 parent 504232b commit b7249ce
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 35 deletions.
78 changes: 43 additions & 35 deletions users/recordservice/record-service.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const Record = require('./record-model')
const Record = require('./record-model');
const { SystemUpdate } = require('@material-ui/icons');

const app = express();
const port = 8004;

// Middleware to parse JSON in request body
app.use(bodyParser.json());

var ranking = [];
var lastTime = new Date();
const minTimeDifferenceInMiliseconds = 120_000;

// Connect to MongoDB
const mongoUri = process.env.MONGODB_URI || 'mongodb://localhost:27017/userdb';
mongoose.connect(mongoUri);
Expand Down Expand Up @@ -44,24 +49,8 @@ app.post('/record', async (req, res) => {

app.get('/record/ranking/top10', async (req, res) => {
try {
const usersCompetitiveStats = await Record.aggregate([
// Unwind the games array to work with each game separately
{ $unwind: "$games" },
// Match only competitive games
{ $match: { "games.competitive": true } },
// Group by user and calculate total points and total competitive games per user
{
$group: {
_id: "$user",
totalPoints: { $sum: "$games.points" },
totalCompetitiveGames: { $sum: 1 } // Count the number of competitive games
}
},
// Sort by total points in descending order (top 1 will have the highest points)
{ $sort: { totalPoints: -1 } },
// Limit to the top 10
{ $limit: 10 }
]);
let usersRanking = await getRanking();
let usersCompetitiveStats = usersRanking.slice(0, 10);

res.json({usersCompetitiveStats: usersCompetitiveStats });
} catch (err) {
Expand All @@ -72,25 +61,13 @@ app.get('/record/ranking/top10', async (req, res) => {
app.get('/record/ranking/:user', async (req, res) => {
try {
const user = req.params.user.toString();
//Gives back an array of 1 user
const userCompetitiveStats = await Record.aggregate([
{ $match: { user: user } },
// Unwind the games array to work with each game separately
{ $unwind: "$games" },
// Match only competitive games
{ $match: { "games.competitive": true } },
// Group by user and calculate total points and total competitive games per user
{
$group: {
_id: "$user",
totalPoints: { $sum: "$games.points" },
totalCompetitiveGames: { $sum: 1 } // Count the number of competitive games
}
}
]);

let usersRanking = await getRanking();
let userCompetitiveStats = usersRanking.filter(userData => userData._id === user);

res.json({userCompetitiveStats: userCompetitiveStats[0] });
} catch (err) {
console.log(err)
res.status(500).send();
}
});
Expand All @@ -108,6 +85,37 @@ app.get('/record/:user', async (req, res) => {
}
});


async function getRanking(){
const nowTime = new Date();
let timeDifferenceInMiliseconds = nowTime - lastTime;
if(ranking.length == 0 || timeDifferenceInMiliseconds > minTimeDifferenceInMiliseconds){
ranking = await Record.aggregate([
// Unwind the games array to work with each game separately
{ $unwind: "$games" },
// Match only competitive games
{ $match: { "games.competitive": true } },
// Group by user and calculate total points and total competitive games per user
{
$group: {
_id: "$user",
totalPoints: { $sum: "$games.points" },
totalCompetitiveGames: { $sum: 1 } // Count the number of competitive games
}
},
// Sort by total points in descending order (top 1 will have the highest points)
{ $sort: { totalPoints: -1 } }
]);

//The operator ... dumps the user json making it {_id , totalPoints, totalCompetitiveGames, position}
ranking = ranking.map((user, index) => ({ ...user, position: index + 1 }));
lastTime = new Date();
}

return ranking;

}

const server = app.listen(port, () => {
console.log(`Record Service listening at http://localhost:${port}`);
});
Expand Down
1 change: 1 addition & 0 deletions users/recordservice/record-service.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,7 @@ describe('Record Service', () => {
const userStats = responseGet.body.userCompetitiveStats;

expect(userStats).toHaveProperty('_id', 'user1');
expect(userStats).toHaveProperty('position', 10);
expect(userStats).toHaveProperty('totalCompetitiveGames', 2);
expect(userStats).toHaveProperty('totalPoints', 20); //i * 10 * totalCompetitiveGames , i = 2
});
Expand Down

0 comments on commit b7249ce

Please sign in to comment.