Skip to content

Commit

Permalink
Merge pull request #88 from Arquisoft/Develop
Browse files Browse the repository at this point in the history
Develop
  • Loading branch information
uo289097 authored Mar 6, 2024
2 parents cdc179c + 3a09314 commit 789c060
Show file tree
Hide file tree
Showing 27 changed files with 621 additions and 332 deletions.
3 changes: 2 additions & 1 deletion gameservice/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,5 @@ COPY . .
EXPOSE 8005

# Define the command to run your app
CMD ["node", "game-service.js"]
CMD ["node", "game-service.js"]

7 changes: 4 additions & 3 deletions gameservice/game-model.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,19 @@ const mongoose = require('mongoose');
const gameSchema = new mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true,
},
questions: {
type: mongoose.Schema.Types.ObjectId,
questions: {
type: [mongoose.Schema.Types.ObjectId],
ref: 'Question',
required: true,
},
answers: [
{
response: {
type: String,
required: true,
required: true,
},
isCorrect: {
type: Boolean,
Expand Down
52 changes: 46 additions & 6 deletions gameservice/game-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ const port = 8005; // Puerto para el servicio de juegos

app.use(express.json());

// Connect to MongoDB
const mongoUri = process.env.MONGODB_URI || 'mongodb://localhost:27017/gamesdb';
mongoose.connect(mongoUri);

// Función para validar campos requeridos
const validateRequiredFields = (req, fields) => {
for (const field of fields) {
Expand Down Expand Up @@ -34,20 +38,56 @@ app.post('/addgame', async (req, res) => {
// Guarda el nuevo juego en la base de datos
const savedGame = await newGame.save();

res.status(201).json(savedGame);
res.status(200).json(savedGame);
} catch (error) {
res.status(500).json({ error: 'Internal Server Error' });
res.status(500).json({ error: error.message });
}
});

// Lógica para juegos??
// Ruta para obtener datos de participación del usuario
app.get('/getParticipation/:userId', async (req, res) => {
try {
const userId = req.params.userId;

// Conecta a la base de datos de juegos
const mongoUri = process.env.MONGODB_URI || 'mongodb://localhost:27017/gamesdb';
mongoose.connect(mongoUri);
// Consulta para obtener los datos de participación del usuario
const participationData = await Game.aggregate([
{ $match: { user: mongoose.Types.ObjectId(userId) } },
{
$group: {
_id: null,
totalGames: { $sum: 1 }, //$sum -> Returns a sum of numerical values
correctAnswers: { $sum: { $size: {
$filter: {
input: "$answers", as: "answer", cond: "$$answer.isCorrect" }
} } },
incorrectAnswers: { $sum: { $size: {
$filter: { input: "$answers", as: "answer", cond: { $eq: ["$$answer.isCorrect", false] } }
} } },
totalTime: { $sum: "$totalTime" },
},
},
]);

if (participationData.length === 0) {
// No se encontraron datos para el usuario
res.status(404).json({ error: 'No participation data found for the user.' });
return;
}

res.status(200).json(participationData[0]);
} catch (error) {
console.error('Error al obtener datos de participación:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});

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

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

module.exports = server;
9 changes: 5 additions & 4 deletions gameservice/game-service.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
const request = require('supertest');
const { MongoMemoryServer } = require('mongodb-memory-server');
const mongoose = require('mongoose');

let mongoServer;
let app;
Expand All @@ -20,8 +19,10 @@ afterAll(async () => {
describe('Game Service', () => {
it('should add a new game on POST /addgame', async () => {
const newGame = {
user: mongoose.Types.ObjectId(), // ID de usuario simulado
questions: mongoose.Types.ObjectId(), // ID de pregunta simulado
user: '609c6e365308ce1a1c2658d1',
questions: [
"609c6e365308ce1a1c2658d2", "609c6e365308ce1a1c2658d3"
],
answers: [
{
response: 'User response',
Expand All @@ -32,7 +33,7 @@ describe('Game Service', () => {
};

const response = await request(app).post('/addgame').send(newGame);
expect(response.status).toBe(201);
expect(response.status).toBe(200);
expect(response.body).toHaveProperty('user', newGame.user.toString());
});
});
2 changes: 1 addition & 1 deletion gameservice/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,4 @@
"mongodb-memory-server": "^9.1.6",
"supertest": "^6.3.4"
}
}
}
14 changes: 7 additions & 7 deletions gatewayservice/gateway-service.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ describe('Gateway Service', () => {
}else if (url.endsWith('/addquestion')) {
return Promise.resolve({
data: {
question: 'What is the capital of France?',
options: ['Paris', 'Berlin', 'Madrid', 'Rome'],
correctOptionIndex: 0
question: 'Mocked Question',
correct: 'Mocked Correct Answer',
incorrects: ['Mocked Option 1', 'Mocked Option 2']
}
});
}
Expand Down Expand Up @@ -100,12 +100,12 @@ describe('Gateway Service', () => {
const response = await request(app)
.post('/addquestion')
.send({
question: 'What is the capital of France?',
options: ['Paris', 'Berlin', 'Madrid', 'Rome'],
correctOptionIndex: 0,
question: 'Mocked Question',
correct: 'Mocked Correct Answer',
incorrects: ['Mocked Option 1', 'Mocked Option 2']
});

expect(response.statusCode).toBe(200);
expect(response.body).toHaveProperty('question', 'What is the capital of France?');
expect(response.body).toHaveProperty('question', 'Mocked Question');
});
});
Loading

0 comments on commit 789c060

Please sign in to comment.