Skip to content

Commit

Permalink
Pasa todo menos /saveGame
Browse files Browse the repository at this point in the history
  • Loading branch information
CANCI0 committed Apr 11, 2024
1 parent 79951ef commit 7708884
Show file tree
Hide file tree
Showing 2 changed files with 125 additions and 44 deletions.
97 changes: 67 additions & 30 deletions statsservice/stats-service.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
// user-service.js
const express = require("express");
const bodyParser = require("body-parser");
const cors = require('cors');
const cors = require("cors");
const Stats = require("./model/stats-model.js");
const StatsForUser = require("./model/stats-getter.js");
const mongoose = require('mongoose');
const mongoose = require("mongoose");

const statsGetter= new StatsForUser();
const app = express();
const port = 8004;

Expand All @@ -15,7 +13,8 @@ app.use(cors());

app.set("json spaces", 40);

const mongoUri = process.env.MONGODB_STATS_URI || 'mongodb://localhost:27017/statsdb';
const mongoUri =
process.env.MONGODB_STATS_URI || "mongodb://localhost:27017/statsdb";
mongoose.connect(mongoUri);

app.post("/saveGame", async (req, res) => {
Expand All @@ -24,13 +23,23 @@ app.post("/saveGame", async (req, res) => {
const gamemode = req.body.gameMode;
const gameData = req.body.gameData;

if (gamemode == "clasico" || gamemode == "bateria" || gamemode =="calculadora") {
if (
gamemode == "clasico" ||
gamemode == "bateria" ||
gamemode == "calculadora"
) {
// Buscar las estadísticas existentes del usuario y modo de juego
let stats = await Stats.findOne({ username: username, gamemode: gamemode });
let stats = await Stats.findOne({
username: username,
gamemode: gamemode,
});
if (!stats) {
var ratioCorrect=0;
if(gameData.incorrectAnswers + gameData.correctAnswers>0){
ratioCorrect=(gameData.correctAnswers / (gameData.incorrectAnswers + gameData.correctAnswers)) * 100;
var ratioCorrect = 0;
if (gameData.incorrectAnswers + gameData.correctAnswers > 0) {
ratioCorrect =
(gameData.correctAnswers /
(gameData.incorrectAnswers + gameData.correctAnswers)) *
100;
}
// Si no existen estadísticas, crear un nuevo documento
stats = new Stats({
Expand All @@ -46,7 +55,6 @@ app.post("/saveGame", async (req, res) => {
});
await stats.save();
} else {

await Stats.updateOne(
{ username: username, gamemode: gamemode },
{
Expand All @@ -57,10 +65,20 @@ app.post("/saveGame", async (req, res) => {
totalIncorrectQuestions: gameData.incorrectAnswers,
},
$set: {
avgPoints: (stats.avgPoints * stats.nGamesPlayed + gameData.points) / (stats.nGamesPlayed + 1),
ratioCorrect: ((stats.totalCorrectQuestions + gameData.correctAnswers) / (stats.totalIncorrectQuestions + stats.totalCorrectQuestions + gameData.incorrectAnswers + gameData.correctAnswers)) * 100,
avgTime: (stats.avgTime * stats.nGamesPlayed + gameData.avgTime) / (stats.nGamesPlayed + 1),
}
avgPoints:
(stats.avgPoints * stats.nGamesPlayed + gameData.points) /
(stats.nGamesPlayed + 1),
ratioCorrect:
((stats.totalCorrectQuestions + gameData.correctAnswers) /
(stats.totalIncorrectQuestions +
stats.totalCorrectQuestions +
gameData.incorrectAnswers +
gameData.correctAnswers)) *
100,
avgTime:
(stats.avgTime * stats.nGamesPlayed + gameData.avgTime) /
(stats.nGamesPlayed + 1),
},
}
);
}
Expand All @@ -72,38 +90,57 @@ app.post("/saveGame", async (req, res) => {
}
});


app.get("/stats", async (req, res) => {
try {
var data = await statsGetter.getStatsForUser(req.query.user,req.query.gamemode);

res.json(data);

var data = await Stats.findOne({
username: req.query.username,
gamemode: req.query.gamemode,
});
if (!data) {
res.status(400).json({ error: "User not found" });
} else {
res.json(data);
}
} catch (error) {
res.status(400).json({ error: "Error al obtener las estadísticas:"+error.message });
res
.status(400)
.json({ error: "Error al obtener las estadísticas:" + error.message });
}
});

app.get("/ranking", async (req, res) => {
try {
var data = await statsGetter.getRanking(req.query.gamemode,req.query.filterBy);
res.json(data);
let sortBy = req.query.filterBy;
let gamemode = req.query.gamemode;

var data = await Stats.find({ gamemode: gamemode })
.sort(sortBy)
.limit(10);

if (data && data.length > 0) {
data = data.map((stat) => ({
username: stat.username,
[sortBy]: stat[sortBy],
}));
} else {
throw new Error("No se encontraron estadísticas");
}

res.json(data);
} catch (error) {

res.status(400).json({ error: "Error al obtener el ranking: "+error.message });
res
.status(400)
.json({ error: "Error al obtener el ranking: " + error.message });
}
});



const server = app.listen(port, () => {
console.log(`Stats Service listening at http://localhost:${port}`);
});

server.on('close', () => {
server.on("close", () => {
// Close the Mongoose connection
mongoose.connection.close();
});
module.exports = server;

module.exports = server;
72 changes: 58 additions & 14 deletions statsservice/stats-service.test.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
const request = require("supertest");
const { MongoMemoryServer } = require("mongodb-memory-server");
const Stats = require("./model/stats-model");
const statsResponse = require("./statsResponseExample.json");

let mongoServer;
let app;
let stats;
let Stats;

const username = "testusername";
const responseExample = {
Expand All @@ -19,6 +19,17 @@ const responseExample = {
avgTime: 45
}

const responseExample2 = {
"username": "admin",
"gamemode": "clasico",
"gameData": {
"correctAnswers": 1,
"incorrectAnswers": 1,
"points": 1,
"avgTime": 2
}
}

async function addStat(responseExample) {
const newStat = new Stats(responseExample);

Expand All @@ -30,7 +41,7 @@ beforeAll(async () => {
const mongoUri = mongoServer.getUri();
process.env.MONGODB_STATS_URI = mongoUri;
app = require("./stats-service");
stats = require("./model/stats-model");
Stats = require("./model/stats-model");
await addStat(responseExample);
});

Expand All @@ -40,28 +51,61 @@ afterAll(async () => {
});

describe("Stats Service", () => {
it("should save stats successfully", async () => {
const response = await request(app).post("/saveGame").send(responseExample);
it("should save game data successfully", async () => {
jest.setTimeout(10000000); // Set maximum timeout to 10 seconds
const response = await request(app).post("/saveGame").send(responseExample2);
expect(response.status).toBe(200);

expect(response.body).toHaveProperty("username", username);
expect(response.body).toHaveProperty("gamemode", "exampleGamemode");
expect(response.body).toHaveProperty("nGamesPlayed", 11);
expect(response.body).toHaveProperty("avgPoints", 82.27272727272727);
expect(response.body).toHaveProperty("totalPoints", 905);
expect(response.body).toHaveProperty("totalCorrectQuestions", 170);
expect(response.body).toHaveProperty("totalIncorrectQuestions", 60);
expect(response.body).toHaveProperty("ratioCorrect", 0.7391304347826086);
expect(response.body).toHaveProperty("avgTime", 47.72727272727273);
}, 10000000);

it("should return user statistics successfully", async () => {
const response = await request(app).get(
`/stats/?username=${username}&gamemode=exampleGamemode`
);
expect(response.status).toBe(200);
expect(response.body).toEqual({
success: true,
message: "Game saved successfully",
});

expect(response.body).toHaveProperty("nGamesPlayed", 10)
expect(response.body).toHaveProperty("avgPoints", 75.5)
expect(response.body).toHaveProperty("totalPoints", 755)
expect(response.body).toHaveProperty("totalCorrectQuestions", 150)
expect(response.body).toHaveProperty("totalIncorrectQuestions", 50)
expect(response.body).toHaveProperty("ratioCorrect", 0.75)
expect(response.body).toHaveProperty("avgTime", 45);
});

it("should return user statistics successfully", async () => {
it("should return ranking successfully", async () => {
const response = await request(app).get(
`/stats/?user=${username}&gamemode=exampleGamemode`
`/ranking/?gamemode=exampleGamemode&filterBy=avgPoints`
);
expect(response.status).toBe(200);
expect(response.body).toEqual(responseExample);

expect(response.body).toHaveLength(1);
expect(response.body[0]).toHaveProperty("username", username);
expect(response.body[0]).toHaveProperty("avgPoints", 75.5);
});

it("ranking should return error", async () => {
const response = await request(app).get(
`/ranking/?gamemode=exampleGamemodx&filterBy=avgPoints`
);
expect(response.status).toBe(400);

expect(response.body).toHaveProperty("error", "Error al obtener el ranking: No se encontraron estadísticas");
});

it("should return status 400 for incomplete game data", async () => {
const response = await request(app).get(
`/stats/?user=${username}&gamemode=exampleGamemode`
`/stats/?username=${username}`
);
expect(response.status).toBe(200);
expect(response.status).toBe(400);
});
});

0 comments on commit 7708884

Please sign in to comment.