Skip to content

Commit

Permalink
Merge branch 'develop' of https://github.com/Arquisoft/wiq_es05b into…
Browse files Browse the repository at this point in the history
… develop
  • Loading branch information
UO276255 committed Apr 28, 2024
2 parents dc31f8b + bb4b250 commit db6f7b2
Show file tree
Hide file tree
Showing 23 changed files with 90 additions and 74 deletions.
1 change: 1 addition & 0 deletions cyt-utils/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@ module.exports = {
responseLoggerMiddleware: require('./logging/middleware/ResLoggerMiddleware'),
i18nextInitializer: require('./i18n/i18nextInitializer'),
i18nextMiddleware: require('./i18n/i18nextMiddleware'),
fieldChecker: require('./validation/fieldChecker'),
}
8 changes: 4 additions & 4 deletions cyt-utils/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion cyt-utils/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "cyt-utils",
"version": "2.2.0",
"version": "2.4.0",
"description": "A variety of utilities for the project",
"main": "index.js",
"scripts": {
Expand Down
7 changes: 7 additions & 0 deletions cyt-utils/validation/fieldChecker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const fieldChecker = (fields, obj) => {
for (let field of fields)
if (!(field in obj)) return field;
return null;
}

module.exports = fieldChecker;
10 changes: 3 additions & 7 deletions gatewayservice/middleware/AuthTokenMiddleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,9 @@ module.exports = (i18next) => (req, res, next) => {
const { userIdToken } = req
let userId

if("userId" in req.params) {
userId = req.params.userId
} else if ("userId" in req.body) {
userId = req.body.userId
} else {
userId = req.query.userId
}
if("userId" in req.params) userId = req.params.userId
else if ("userId" in req.body) userId = req.body.userId
else userId = req.query.userId

if(!userId) return next({status: 400, error: `${i18next.t("error_missing_field")} userId`})
if (userIdToken && userIdToken !== userId) return next({ status: 401, error: i18next.t("error_save_property") })
Expand Down
2 changes: 0 additions & 2 deletions gatewayservice/routes/jordiRoutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,6 @@ module.exports = (app, axios) => {
);
});

// TODO - Check n is a number -> error 400
// TODO - If no category is found -> error 404
app.get("/game/questions/:category/:n", async (req, res, next) => {
axios
.get(`${questionServiceUrl}/questions/${req.params.category}/${req.params.n}`)
Expand Down
2 changes: 1 addition & 1 deletion gatewayservice/routes/usersRoutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ module.exports = (app, axios, authTokenMiddleware) => {
let e = error.error || i18next.t("error_login_service_unable")
if (error.code && error.code.includes("ECONNREFUSED"))
e = { error: i18next.t("error_service_unavailable") }
res.status(200).json({ message: response.data.message, error: e })
res.json({ message: response.data.message, error: e })
})
})
.catch(() => next({ error: i18next.t("error_adding_user") }));
Expand Down
2 changes: 2 additions & 0 deletions gatewayservice/utils/FieldChecker.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@

// TODO - Move to npm package
const checkFieldsOn = (fields, obj) => {
for (let field of fields)
if (!(field in obj)) return field;
Expand Down
2 changes: 2 additions & 0 deletions jordi/locals/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
"error_invalid_n": "'n' must be a number",
"error_group_not_found": "Group not found",
"error_group_exists": "Already existing groups detected",
"error_question_not_found": "Question not found",
"error_category_not_found": "Category not found",

"group_questions_generated": "Questions generated successfully: ",
"all_questions_generated": "All questions generated successfully",
Expand Down
2 changes: 2 additions & 0 deletions jordi/locals/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
"error_invalid_n": "'n' debe ser un numero",
"error_group_not_found": "Grupo no encontrado",
"error_group_exists": "Already existing groups detected",
"error_question_not_found": "Pregunta no encontrada",
"error_category_not_found": "Categoria no encontrada",

"group_questions_generated": "Preguntas generadas correctamente: ",
"all_questions_generated": "Todas las preguntas generadas correctamente",
Expand Down
11 changes: 11 additions & 0 deletions jordi/repositories/questionRepository.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,17 @@ module.exports = {
}
},

checkCategory: async function (category) {
try {
await this.checkUp();
return await this.mongoose.connection
.collection(this.collectionName)
.findOne({ categories: category });
} catch (e) {
throw e.message;
}
},

getQuestions: async function (category, n = 10) {
try {
await this.checkUp();
Expand Down
9 changes: 6 additions & 3 deletions jordi/routes/jordi-ask.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,19 @@ module.exports = function (app, questionsRepository) {

questionsRepository
.findQuestionById(req.params.id)
.then(result => res.json(result))
.then(result => {
if(!result) return next({status: 404, error: i18next.t("error_question_not_found")})
res.json(result)
})
.catch(err => next(err));
})

// TODO: Should return 404 if category not found
// TODO: Check n is a number -> error 400
app.get('/questions/:category/:n', async (req, res, next) => {
const {category, n} = req.params;

if(isNaN(n)) return next({status: 400, error: i18next.t("error_invalid_n")})
const c = await questionsRepository.checkCategory(category);
if(!c) return next({status: 404, error: i18next.t("error_category_not_found")})

questionsRepository.getQuestions(category, n)
.then(result => {
Expand Down
35 changes: 7 additions & 28 deletions jordi/routes/jordi-think.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,81 +8,60 @@ module.exports = function (app, questionsRepository, groupsRepository) {
app.get("/gen/:groupId", async (req, res, next) => {

try {

const { groupId } = req.params;

let group = await groupsRepository.findGroups({ groupId: groupId });

if (!group[0]) return next({ status: 404, error: i18next.t("error_group_not_found") });

group = group[0];

const generator = new WikidataGenerator(group);

const questions = await generator.generate()

await questionsRepository.deleteQuestions(groupId)
await questionsRepository.insertQuestions(questions)
res.json({ message: i18next.t("group_questions_generated") + groupId });
console.log("Questions generated successfully: " + groupId)
} catch (error) {
next(error);
}
} catch (error) { next(error); }

});

app.get("/gen", async (req, res, next) => {
try {
await script(groupsRepository, questionsRepository, WikidataGenerator);
res.json({ message: i18next.t("all_questions_generated") });

} catch (error) {
next(error);
}
} catch (error) { next(error); }
});

app.get("/groups", async (req, res, next) => {
try {
const groups = await groupsRepository.findGroups({});
res.json(groups);
} catch (error) {
next(error);
}
} catch (error) { next(error); }
});

app.post("/addGroups", async (req, res, next) => {
try {

const groups = req.body;

for (let group of groups) {
for (let group of groups)
await groupsRepository.insertGroup(group);
}

res.json({ message: i18next.t("groups_added") })

} catch (error) {
next(error);
}
} catch (error) { next(error); }
});

app.get("/removeGroup/:groupId", async (req, res, next) => {
try {
const { groupId } = req.params;
await groupsRepository.removeGroups({ groupId: groupId });
res.json({ message: i18next.t("group_removed") })
} catch (error) {
next(error);
}
} catch (error) { next(error); }
});

app.get("/removeAllGroups", async (req, res, next) => {
try {
await groupsRepository.removeGroups();
res.json({ message: i18next.t("all_groups_removed") });
} catch (error) {
next(error);
}
} catch (error) { next(error); }
});

}
20 changes: 2 additions & 18 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,27 +1,11 @@
{
"scripts": {
"mongo": "docker run -d -p 27017:27017 --name=my-mongo mongo:latest",
"postgres": "docker run -d --name my_postgres -e POSTGRES_PASSWORD=jordishhh -p 5432:5432 postgres:latest",
"webapp": "cd webapp && npm start",
"gateway": "cd gatewayservice && npm start",
"auth": "cd users/authservice && npm start",
"user": "cd users/userservice && npm start",
"think": "cd jordi/jordi-think && npm start",
"ask": "cd jordi/jordi-ask && npm start",
"ranking": "cd ranking && npm start"
},
"dependencies": {
"axios": "^1.6.8",
"bcrypt": "^5.1.1",
"es6": "^0.0.7",
"express": "^4.19.2",
"mongodb-memory-server": "^9.1.8",
"mongoose": "^8.3.0",
"node-cron": "^3.0.3",
"supertest": "^6.3.4"
},
"devDependencies": {
"jest": "^29.7.0",
"typescript": "^5.4.3"
"jordi": "cd jordi && npm start",
"history": "cd userhistory && npm start"
}
}
1 change: 0 additions & 1 deletion userhistory/history-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,5 +62,4 @@ server.on('close', () => {
cron.getTasks().forEach(task => task.stop())
});


module.exports = server
8 changes: 3 additions & 5 deletions userhistory/routes/historyRoutes.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@

// TODO - move to npm package
const checkFieldsOn = (fields, obj) => {
for (let field of fields)
if (!(field in obj)) return field;
Expand All @@ -7,7 +9,6 @@ const checkFieldsOn = (fields, obj) => {
module.exports = (app, saveRepository) => {
const i18next = app.get("i18next");

// TODO - Add error mapping
app.post("/create", (req, res, next) => {
const result = checkFieldsOn(["userId", "category"], req.body)
if(result) return next({status: 400, error: `${i18next.t("error_missing_field")} ${result}`})
Expand All @@ -23,7 +24,6 @@ module.exports = (app, saveRepository) => {
.catch(error => next(error))
})

// TODO - Add error mapping
// TODO - Gateway should check if the user is owner of the save
app.post("/add/:id", (req, res, next) => {
const { id } = req.params;
Expand All @@ -47,7 +47,6 @@ module.exports = (app, saveRepository) => {
.catch((e) => next(e));
});

// TODO - Add error mapping
app.get("/get/:userId", (req, res, next) => {
const { userId } = req.params;
if (!saveRepository.isValidObjectId(userId)) return next({ status: 400, error: i18next.t("error_invalid_userId")})
Expand All @@ -64,7 +63,6 @@ module.exports = (app, saveRepository) => {
.catch((e) => next(e));
});

// TODO - Add error mapping
app.get("/get/:userId/:id", (req, res, next) => {
const { userId, id } = req.params;
if (!saveRepository.isValidObjectId(userId)) return next({status: 400, error: i18next.t("error_invalid_userId")})
Expand Down Expand Up @@ -92,7 +90,7 @@ module.exports = (app, saveRepository) => {

saveRepository
.getRanking(Number(n), order)
.then((result) => res.status(200).json(result))
.then((result) => res.json(result))
.catch((error) => next(error));
});
};
1 change: 1 addition & 0 deletions users/authservice/routes/authRoutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const jwt = require('jsonwebtoken');
// TODO - Move to GH secret
const JWT_SECRET = process.env.SECRET || "a-very-secret-string"

// TODO - Move to npm package
const checkFieldsOn = (fields, obj) => {
for (let field of fields)
if (!(field in obj)) return field;
Expand Down
3 changes: 2 additions & 1 deletion users/userservice/.env
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
MONGODB_URI="mongodb://localhost:27017/userdb"
MONGODB_URI="mongodb://localhost:27017/userdb"
ADMIN_PASSWORD="admin"
1 change: 1 addition & 0 deletions users/userservice/locals/en.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
{
"translation": {
"user_created": "User created successfully",
"error_invalid_id": "Invalid id format",
"error_user_exists": "Username already exists",
"error_user_not_found": "User not found",
Expand Down
1 change: 1 addition & 0 deletions users/userservice/locals/es.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
{
"translation": {
"user_created": "Usuario creado correctamente",
"error_invalid_id": "Formato de ID inválido",
"error_user_exists": "El usuario ya existe",
"error_user_not_found": "Usuario no encontrado",
Expand Down
2 changes: 2 additions & 0 deletions users/userservice/middleware/DataMiddleware.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@

// TODO - Move to npm package
const checkFieldsOn = (fields, obj) => {
for (const field of fields)
if (!obj[field]) return field;
Expand Down
Loading

0 comments on commit db6f7b2

Please sign in to comment.