Skip to content
This repository has been archived by the owner on May 10, 2024. It is now read-only.

Commit

Permalink
Merge pull request #141 from Arquisoft/develop
Browse files Browse the repository at this point in the history
Develop
  • Loading branch information
RubenFern committed Mar 10, 2024
2 parents f83f44b + ba7b453 commit 5545da7
Show file tree
Hide file tree
Showing 45 changed files with 35,951 additions and 26,821 deletions.
10 changes: 10 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,16 @@ services:
networks:
- mynetwork

mongodb:
container_name: mongodb-${teamname:-defaultASW}
image: mongo
restart: always
profiles: [ "dev", "prod" ]
ports:
- 27017:27017
networks:
- mynetwork

webapp:
container_name: webapp-${teamname:-defaultASW}
image: ghcr.io/arquisoft/wiq_es1c/webapp:latest
Expand Down
1 change: 1 addition & 0 deletions game_service/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
MONGODB_URI="mongodb://mongodb:27017/wiq"
4 changes: 4 additions & 0 deletions game_service/db/models/question.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ const Question = database.define('Question', {
type: DataTypes.STRING,
allowNull: false,
},
imageUrl: {
type: DataTypes.STRING,
allowNull: true,
},
answer: {
type: DataTypes.STRING,
allowNull: false,
Expand Down
27 changes: 27 additions & 0 deletions game_service/db/mongo/config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
const mongoose = require("mongoose");
const { MongoMemoryServer } = require('mongodb-memory-server');

const connect = async() =>
{
try
{
if (process.env.DB_URL) {
await mongoose.connect('mongodb://mongodb:27017/wiq')
console.log("MongoDB Server Selected")
} else {
const mongoServer = await MongoMemoryServer.create();
const mongoUri = mongoServer.getUri();
await mongoose.connect(mongoUri)

console.log("MongoDB RAM MEMORY SERVER Selected")
}

console.log('MongoDB connected');
}
catch(error) {
console.log(error);
throw new Error('Error to connect with MongoDB');
}
}

module.exports = connect;
39 changes: 39 additions & 0 deletions game_service/db/mongo/schema/Question.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
const { Schema, model } = require("mongoose");


const Question = Schema
({
title: {
type: String,
required: true,
trim: true
},
answer: {
type: String,
required: true,
trim: true
},
fakes: {
type: [String],
required: true
},
imageUrl: {
type: String,
default: ""
},
createdAt: {
type: Date,
default: Date.now
}
});

Question.methods.toJSON = function()
{
const { __v, _id, ...question } = this.toObject();

question.uid = _id;

return question;
}

module.exports = model('Question', Question);
16 changes: 16 additions & 0 deletions game_service/game.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
// External libs
require('dotenv').config()
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const jwt = require('jsonwebtoken');
const axios = require('axios');
const mongodb = require('./db/mongo/config');

// My own libs
const authMiddleware = require('./auth/authMiddleware');
const sync = require("./db/sync");
const {newGame, next, awnser, update} = require("./game/endpoints");
const { saveQuestionsInDB, deleteOlderQuestions, loadInitialQuestions } = require('./services/questionsService');

const port = 8003;
const app = express();
Expand All @@ -24,6 +27,19 @@ app.post('/api/game/next', next);
app.post('/api/game/awnser', awnser);
app.post('/api/game/update', update);

// Connect with mongodb
mongodb();

// Save questions for each 24 hours
loadInitialQuestions();

//We dont want to do this in a test enviroment

setInterval( async () => {
await deleteOlderQuestions();
await saveQuestionsInDB();
}, 24 * 60 * 60 * 1000);

// Start the server
const server = app.listen(port, () => {
sync();
Expand Down
11 changes: 1 addition & 10 deletions game_service/game.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ beforeAll(async () => {
})

afterAll(async () => {
app.close();
await app.close();
})

jest.mock('axios')
Expand Down Expand Up @@ -83,10 +83,6 @@ describe('Game Service', () => {
expect(response.statusCode).toBe(200);
expect(response.body.title).toBe("Cual es la capital de Chile");
expect(response.body.awnsers.length).toBe(4);
expect(response.body.awnsers[0]).toBe("Santiago");
expect(response.body.awnsers[1]).toBe("Lima");
expect(response.body.awnsers[2]).toBe("Madrid");
expect(response.body.awnsers[3]).toBe("Bogota");
})

it("Should return 200 with an valid token and requesting update", async () => {
Expand All @@ -97,10 +93,6 @@ describe('Game Service', () => {
expect(response.statusCode).toBe(200);
expect(response.body.title).toBe("Cual es la capital de Chile");
expect(response.body.awnsers.length).toBe(4);
expect(response.body.awnsers[0]).toBe("Santiago");
expect(response.body.awnsers[1]).toBe("Lima");
expect(response.body.awnsers[2]).toBe("Madrid");
expect(response.body.awnsers[3]).toBe("Bogota");
expect(response.body.created).toMatch(/\d*/);
expect(response.body.duration).toMatch(/\d*/);
})
Expand All @@ -109,7 +101,6 @@ describe('Game Service', () => {
const response = await request(app)
.post('/api/game/awnser')
.send({ token: validToken, awnser: "Santiago" });
console.log(response)

expect(response.statusCode).toBe(200);
expect(response.text).toBe("Santiago");
Expand Down
10 changes: 10 additions & 0 deletions game_service/game/arrayShuffle.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
// Swap array[i] and array[j]
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}

module.exports = shuffleArray;
43 changes: 24 additions & 19 deletions game_service/game/endpoints.js
Original file line number Diff line number Diff line change
@@ -1,51 +1,55 @@
const jwt = require('jsonwebtoken');
const axios = require('axios');
const User = require("../db/models/user")
const Game = require("../db/models/game")
const Question = require("../db/models/question")
const suffle = require("./arrayShuffle")


const privateKey = "ChangeMePlease!!!!"

const {validate, getCurrentQuestion, requestQuestion} = require("./verification")
const {validate, getCurrentQuestion} = require("./verification");
const { loadQuestion } = require('../services/questionsService');

const next = async (req,res) => {
let userId = jwt.verify(req.body.token, privateKey).user_id;
const userId = jwt.verify(req.body.token, privateKey).user_id;

let user = await User.findOne({
const user = await User.findOne({
where: {
id: userId
}
})

if(user == null){
res.status(400).send();
return;
}

let games = await user.getGames();
const games = await user.getGames();
if(games == null || games.length < 1){
res.status(400).send();
return;
}

let questionRaw = await requestQuestion();
let game = games[0];

const questionRaw = await loadQuestion();
const game = games[0];
Question.create({
title: questionRaw.title,
answer: questionRaw.awnser,
fake: questionRaw.fake,
imageUrl: questionRaw.imageUrl ? questionRaw.imageUrl : "",
answer: questionRaw.answer,
fake: questionRaw.fakes,
GameId: game.id
})

res.status(200).json({
title: questionRaw.title,
awnsers: [
String(questionRaw.awnser),
String(questionRaw.fake[0]),
String(questionRaw.fake[1]),
String(questionRaw.fake[2])
]
imageUrl: questionRaw.imageUrl ? questionRaw.imageUrl : "",
awnsers: suffle([
String(questionRaw.answer),
String(questionRaw.fakes[0]),
String(questionRaw.fakes[1]),
String(questionRaw.fakes[2])
])
});
}

Expand All @@ -72,12 +76,13 @@ const update = async (req, res) => {

res.status(200).json({
title: question.title,
awnsers: [
imageUrl: question.imageUrl ? question.imageUrl : "",
awnsers: suffle([
String(question.answer),
String(question.fake[0]),
String(question.fake[1]),
String(question.fake[2])
],
]),
created: String(question.createdAt.getTime()),
duration: String(question.duration)
});
Expand Down
3 changes: 2 additions & 1 deletion game_service/game/verification.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,11 @@ const getCurrentQuestion = async (user) => {
}

const requestQuestion = async() => {
let res = (await axios.post("http://question:8002/api/questions/generate")).data;

let res = (await axios.post("http://question:8002/api/questions/generate")).data;
return {
"title": res.title,
"imageUrl": res.hasOwnProperty('imageUrl') ? res.imageUrl : "",
"awnser": res.awnser,
"fake" : res.fake
}
Expand Down
2 changes: 2 additions & 0 deletions game_service/game/verification.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ describe('Utils Functions', () => {
data: {
title: 'Sample Question',
awnser: 'Correct Answer',
imageUrl: "",
fake: ['Fake 1', 'Fake 2', 'Fake 3'],
},
};
Expand All @@ -94,6 +95,7 @@ describe('Utils Functions', () => {
expect(result).toEqual({
title: 'Sample Question',
awnser: 'Correct Answer',
imageUrl: "",
fake: ['Fake 1', 'Fake 2', 'Fake 3'],
});
});
Expand Down
Loading

0 comments on commit 5545da7

Please sign in to comment.