diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 2c3ecdf5..6ed9667f 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -21,6 +21,8 @@ jobs: - run: npm --prefix questionservice ci - run: npm --prefix statsservice ci - run: npm --prefix webapp ci + - run: npm --prefix questionservice ci + - run: npm --prefix statsservice ci - run: npm --prefix users/authservice test -- --coverage - run: npm --prefix users/userservice test -- --coverage - run: npm --prefix gatewayservice test -- --coverage diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e5739872..323fa2f8 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -40,6 +40,7 @@ jobs: - run: npm --prefix users/userservice install - run: npm --prefix gatewayservice install - run: npm --prefix questionservice install + - run: npm --prefix statsservice install - run: npm --prefix webapp install - run: npm --prefix webapp run build - run: npm --prefix webapp run test:e2e diff --git a/docker-compose.yml b/docker-compose.yml index 8cd16468..cb3c44be 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -35,6 +35,22 @@ services: environment: MONGODB_URI: mongodb://mongodb:27017/userdb + statsservice: + container_name: statsservice-${teamname:-defaultASW} + image: ghcr.io/arquisoft/wiq_es1a/statsservice:latest + profiles: ["dev", "prod"] + build: ./statsservice + depends_on: + - mongodb + - userservice + ports: + - "8004:8004" + networks: + - mynetwork + environment: + MONGODB_URI: mongodb://mongodb:27017/userdb + USER_SERVICE_URL: http://userservice:8001 + authservice: container_name: authservice-${teamname:-defaultASW} image: ghcr.io/arquisoft/wiq_es1a/authservice:latest @@ -74,12 +90,13 @@ services: - userservice - authservice - questionservice + - statsservice ports: - "8000:8000" networks: - mynetwork environment: - STATS_SERVICE_URL: http://questionservice:8004 + STATS_SERVICE_URL: http://statsservice:8004 QUESTION_SERVICE_URL: http://questionservice:8003 AUTH_SERVICE_URL: http://authservice:8002 USER_SERVICE_URL: http://userservice:8001 diff --git a/gatewayservice/gateway-service.js b/gatewayservice/gateway-service.js index b1c484cf..e5fbe175 100644 --- a/gatewayservice/gateway-service.js +++ b/gatewayservice/gateway-service.js @@ -9,6 +9,7 @@ const port = 8000; const authServiceUrl = process.env.AUTH_SERVICE_URL || 'http://localhost:8002'; const userServiceUrl = process.env.USER_SERVICE_URL || 'http://localhost:8001'; const questionServiceUrl = process.env.QUESTION_SERVICE_URL || 'http://localhost:8003'; +const statsServiceUrl = process.env.AUTH_SERVICE_URL || 'http://localhost:8004'; app.use(cors()); app.use(express.json()); @@ -52,6 +53,46 @@ app.get('/questions', async (req, res) => { } }); +app.get('/stats', async (req, res) => { + try { + // Forward the stats request to the stats service + const statsResponse = await axios.get(statsServiceUrl+'/stats', req.body); + res.json(statsResponse.data); + } catch (error) { + res.status(error.response.status).json({ error: error.response.data.error }); + } +}); + +app.post('/saveGame', async (req, res) => { + try { + // Forward the save game request to the stats service + const gameResponse = await axios.post(statsServiceUrl+'/saveGame', req.body); + res.json(gameResponse.data); + } catch (error) { + res.status(error.response.status).json({ error: error.response.data.error }); + } +}); + +app.get('/getstats', async (req, res) => { + try { + // Forward the stats request to the stats service + const statsResponse = await axios.get(userServiceUrl+'/getstats', req.body); + res.json(statsResponse.data); + } catch (error) { + res.status(error.response.status).json({ error: error.response.data.error }); + } +}); + +app.post('/userSaveGame', async (req, res) => { + try { + // Forward the save game request to the stats service + const gameResponse = await axios.post(userServiceUrl+'/userSaveGame', req.body); + res.json(gameResponse.data); + } catch (error) { + res.status(error.response.status).json({ error: error.response.data.error }); + } +}); + // Start the gateway service const server = app.listen(port, () => { console.log(`Gateway Service listening at http://localhost:${port}`); diff --git a/package-lock.json b/package-lock.json index 0add4cee..d2381195 100644 --- a/package-lock.json +++ b/package-lock.json @@ -5,6 +5,9 @@ "packages": { "": { "dependencies": { + "axios": "^1.6.7", + "cors": "^2.8.5", + "cron": "^3.1.6", "cross-fetch": "^4.0.0", "date-fns": "^3.3.1", "react-auth-kit": "^3.0.2-alpha.19" @@ -169,6 +172,26 @@ "tslib": "^2.4.0" } }, + "node_modules/@types/luxon": { + "version": "3.3.8", + "resolved": "https://registry.npmjs.org/@types/luxon/-/luxon-3.3.8.tgz", + "integrity": "sha512-jYvz8UMLDgy3a5SkGJne8H7VA7zPV2Lwohjx0V8V31+SqAjNmurWMkk9cQhfvlcnXWudBpK9xPM1n4rljOcHYQ==" + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==" + }, + "node_modules/axios": { + "version": "1.6.7", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.6.7.tgz", + "integrity": "sha512-/hDJGff6/c7u0hDkvkGxR/oy6CbCs8ziCsC7SqmhjfozqiJGc8Z11wrv9z9lYfY4K8l+H9TpjcMDX0xOZmx+RA==", + "dependencies": { + "follow-redirects": "^1.15.4", + "form-data": "^4.0.0", + "proxy-from-env": "^1.1.0" + } + }, "node_modules/busboy": { "version": "1.6.0", "resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz", @@ -207,6 +230,38 @@ "integrity": "sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==", "peer": true }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/cors": { + "version": "2.8.5", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz", + "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/cron": { + "version": "3.1.6", + "resolved": "https://registry.npmjs.org/cron/-/cron-3.1.6.tgz", + "integrity": "sha512-cvFiQCeVzsA+QPM6fhjBtlKGij7tLLISnTSvFxVdnFGLdz+ZdXN37kNe0i2gefmdD17XuZA6n2uPVwzl4FxW/w==", + "dependencies": { + "@types/luxon": "~3.3.0", + "luxon": "~3.4.0" + } + }, "node_modules/cross-fetch": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/cross-fetch/-/cross-fetch-4.0.0.tgz", @@ -224,6 +279,46 @@ "url": "https://github.com/sponsors/kossnocorp" } }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/follow-redirects": { + "version": "1.15.5", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.5.tgz", + "integrity": "sha512-vSFWUON1B+yAw1VN4xMfxgn5fTUiaOzAJCKBwIIgT/+7CuGy9+r+5gITvP62j3RmaD5Ph65UaERdOSRGUzZtgw==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, + "node_modules/form-data": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", + "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/graceful-fs": { "version": "4.2.11", "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", @@ -256,6 +351,33 @@ "loose-envify": "cli.js" } }, + "node_modules/luxon": { + "version": "3.4.4", + "resolved": "https://registry.npmjs.org/luxon/-/luxon-3.4.4.tgz", + "integrity": "sha512-zobTr7akeGHnv7eBOXcRgMeCP6+uyYsczwmeRCauvpvaAltgNyTbLH/+VaEAPUeWBT+1GuNmz4wC/6jtQzbbVA==", + "engines": { + "node": ">=12" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, "node_modules/nanoid": { "version": "3.3.7", "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.7.tgz", @@ -339,6 +461,14 @@ } } }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/picocolors": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.0.0.tgz", @@ -373,6 +503,11 @@ "node": "^10 || ^12 || >=14" } }, + "node_modules/proxy-from-env": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", + "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==" + }, "node_modules/react": { "version": "18.2.0", "resolved": "https://registry.npmjs.org/react/-/react-18.2.0.tgz", @@ -480,6 +615,14 @@ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.6.2.tgz", "integrity": "sha512-AEYxH93jGFPn/a2iVAwW87VuUIkR1FVUKB77NwMF7nBTDkDrrT/Hpt/IrCJ0QXhW27jTBDcf5ZY7w6RiqTMw2Q==" }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/webidl-conversions": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", diff --git a/package.json b/package.json index eed5c7aa..3352cf06 100644 --- a/package.json +++ b/package.json @@ -1,5 +1,8 @@ { "dependencies": { + "axios": "^1.6.7", + "cors": "^2.8.5", + "cron": "^3.1.6", "cross-fetch": "^4.0.0", "date-fns": "^3.3.1", "react-auth-kit": "^3.0.2-alpha.19" diff --git a/statsservice/package-lock.json b/statsservice/package-lock.json index d2dd0912..133a00de 100644 --- a/statsservice/package-lock.json +++ b/statsservice/package-lock.json @@ -9,6 +9,10 @@ "version": "1.0.0", "license": "ISC", "dependencies": { + + "axios": "^1.6.7", + "cors": "^2.8.5", + "express": "^4.18.2", "mongoose": "^8.2.0" } @@ -51,6 +55,23 @@ "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==" }, + + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==" + }, + "node_modules/axios": { + "version": "1.6.7", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.6.7.tgz", + "integrity": "sha512-/hDJGff6/c7u0hDkvkGxR/oy6CbCs8ziCsC7SqmhjfozqiJGc8Z11wrv9z9lYfY4K8l+H9TpjcMDX0xOZmx+RA==", + "dependencies": { + "follow-redirects": "^1.15.4", + "form-data": "^4.0.0", + "proxy-from-env": "^1.1.0" + } + }, + "node_modules/body-parser": { "version": "1.20.1", "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.1.tgz", @@ -75,9 +96,10 @@ } }, "node_modules/bson": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/bson/-/bson-6.3.0.tgz", - "integrity": "sha512-balJfqwwTBddxfnidJZagCBPP/f48zj9Sdp3OJswREOgsJzHiQSaOIAtApSgDQFYgHqAvFkp53AFSqjMDZoTFw==", + "version": "6.4.0", + "resolved": "https://registry.npmjs.org/bson/-/bson-6.4.0.tgz", + "integrity": "sha512-6/gSSEdbkuFlSb+ufj5jUSU4+wo8xQOwm2bDSqwmxiPE17JTpsP63eAwoN8iF8Oy4gJYj+PAL3zdRCTdaw5Y1g==", + "engines": { "node": ">=16.20.1" } @@ -108,6 +130,17 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, "node_modules/content-disposition": { "version": "0.5.4", "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", @@ -140,6 +173,18 @@ "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", "integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==" }, + "node_modules/cors": { + "version": "2.8.5", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz", + "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + } + }, "node_modules/debug": { "version": "2.6.9", "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", @@ -164,6 +209,14 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "engines": { + "node": ">=0.4.0" + } + }, "node_modules/depd": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", @@ -284,6 +337,38 @@ "node": ">= 0.8" } }, + "node_modules/follow-redirects": { + "version": "1.15.5", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.5.tgz", + "integrity": "sha512-vSFWUON1B+yAw1VN4xMfxgn5fTUiaOzAJCKBwIIgT/+7CuGy9+r+5gITvP62j3RmaD5Ph65UaERdOSRGUzZtgw==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, + "node_modules/form-data": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", + "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/forwarded": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", @@ -617,6 +702,15 @@ "node": ">= 0.6" } }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { "version": "1.13.1", "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.1.tgz", @@ -661,6 +755,11 @@ "node": ">= 0.10" } }, + "node_modules/proxy-from-env": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", + "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==" + }, "node_modules/punycode": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", diff --git a/statsservice/package.json b/statsservice/package.json index 6f948bef..a13dc26c 100644 --- a/statsservice/package.json +++ b/statsservice/package.json @@ -10,6 +10,8 @@ "author": "", "license": "ISC", "dependencies": { + "axios": "^1.6.7", + "cors": "^2.8.5", "express": "^4.18.2", "mongoose": "^8.2.0" } diff --git a/statsservice/stats-service.js b/statsservice/stats-service.js index fef1c0cb..43eabc05 100644 --- a/statsservice/stats-service.js +++ b/statsservice/stats-service.js @@ -1,15 +1,14 @@ // user-service.js const express = require("express"); const bodyParser = require("body-parser"); -const StatsForUser = require("./model/stats-getter"); -const User = require("./user-model"); - +const cors = require('cors'); +const axios = require('axios'); const app = express(); const port = 8004; -const statsGetter = new StatsForUser(); app.use(bodyParser.json()); +app.use(cors()); app.set("json spaces", 40); @@ -17,19 +16,16 @@ app.post("/saveGame", async (req, res) => { try { const { username, correctAnswers, incorrectAnswers, points, avgTime } = req.body; - // Encontrar al usuario en la base de datos - const user = await User.findOne({ username }); - - if (!user) { - return res.status(404).json({ error: "Usuario no encontrado" }); - } - - // Crear un nuevo juego - const newGame = { + // Hacer una solicitud al servicio user-service para guardar el juego + const response = await axios.post('http://localhost:8001/userSaveGame', { + username, correctAnswers, incorrectAnswers, points, avgTime + }); + + res.json(response.data); }; user.games.push(newGame); @@ -42,22 +38,24 @@ app.post("/saveGame", async (req, res) => { } }); +// Ruta para obtener estadísticas app.get("/stats", async (req, res) => { - if (!statsGetter.existsUser(req.query.user)) { - res - .status(400) - .json({ error: `El usuario no existe` }); - } try { - var data = statsGetter.getStatsForUser(req.query.user); - res.json(data); + const username = req.query.user; + + // Hacer una solicitud al servicio user-service para obtener estadísticas + const response = await axios.get(`http://localhost:8001/getstats?user=${username}`); + + res.json(response.data); } catch (error) { - res.status(400).json({ error: error.message }); + res.status(400).json({ error: `Error al obtener las estadísticas: ${error.message}`}); } }); + + const server = app.listen(port, () => { - console.log(`Stats Service listening at http://localhost:${port}`); - }); + console.log(`Stats Service listening at http://localhost:${port}`); +}); module.exports = server; \ No newline at end of file diff --git a/users/authservice/auth-service.js b/users/authservice/auth-service.js index 20943611..278c4b01 100644 --- a/users/authservice/auth-service.js +++ b/users/authservice/auth-service.js @@ -39,9 +39,6 @@ app.post('/login', async (req, res) => { // Generate a JWT token const token = jwt.sign({ userId: user._id }, 'your-secret-key', { expiresIn: '1h' }); //Almacenamos el token del usuario para su autentificación - sessionStorage.setItem('token', token); - - sessionStorage.setItem('username', username); // Respond with the token and user information res.json({ token: token, username: username, createdAt: user.createdAt }); diff --git a/users/userservice/package-lock.json b/users/userservice/package-lock.json index a21ea706..c91ebfa3 100644 --- a/users/userservice/package-lock.json +++ b/users/userservice/package-lock.json @@ -11,6 +11,7 @@ "dependencies": { "bcrypt": "^5.1.1", "body-parser": "^1.20.2", + "cors": "^2.8.5", "express": "^4.18.2", "mongoose": "^8.2.0" }, @@ -1917,6 +1918,18 @@ "integrity": "sha512-LDx6oHrK+PhzLKJU9j5S7/Y3jM/mUHvD/DeI1WQmJn652iPC5Y4TBzC9l+5OMOXlyTTA+SmVUPm0HQUwpD5Jqw==", "dev": true }, + "node_modules/cors": { + "version": "2.8.5", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz", + "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + } + }, "node_modules/create-jest": { "version": "29.7.0", "resolved": "https://registry.npmjs.org/create-jest/-/create-jest-29.7.0.tgz", diff --git a/users/userservice/package.json b/users/userservice/package.json index f8b4e943..9aad1a22 100644 --- a/users/userservice/package.json +++ b/users/userservice/package.json @@ -20,6 +20,7 @@ "dependencies": { "bcrypt": "^5.1.1", "body-parser": "^1.20.2", + "cors": "^2.8.5", "express": "^4.18.2", "mongoose": "^8.2.0" }, diff --git a/users/userservice/stats-getter.js b/users/userservice/stats-getter.js new file mode 100644 index 00000000..73a3b85b --- /dev/null +++ b/users/userservice/stats-getter.js @@ -0,0 +1,53 @@ +const User = require('./user-model.js'); + + +class StatsForUser { + + async getStatsForUser(username){ + try { + const user = await User.findOne({ username: username }); + + if (!user) { + throw new Error('Usuario no encontrado'); + } + + const partidas = user.games; + + var nGamesPlayed = partidas.length; + var totalPoints = 0; + var totalCorrectQuestions = 0; + var totalIncorrectQuestions = 0; + var avgTime=0; + + for (const partida of partidas){ + totalPoints += partida.points; + totalCorrectQuestions += partida.correctAnswers; + totalIncorrectQuestions += partida.incorrectAnswers; + } + + var avgPoints = nGamesPlayed > 0 ? + totalPoints / nGamesPlayed : 0; + + var ratioCorrectToIncorrect = totalIncorrectQuestions !== 0 ? + totalCorrectQuestions / totalIncorrectQuestions : totalCorrectQuestions; + + var statsJSON = { + username: username, + nGamesPlayed: nGamesPlayed, + avgPoints: avgPoints, + totalPoints: totalPoints, + totalCorrectQuestions: totalCorrectQuestions, + totalIncorrectQuestions: totalIncorrectQuestions, + ratioCorrectToIncorrect: ratioCorrectToIncorrect + }; + + return statsJSON; + } catch (error) { + console.error('Error al obtener las estadísticas del usuario:', error); + throw error; + } + } +} + +module.exports = StatsForUser; + diff --git a/users/userservice/user-service.js b/users/userservice/user-service.js index be958427..b02a6b27 100644 --- a/users/userservice/user-service.js +++ b/users/userservice/user-service.js @@ -3,11 +3,17 @@ const express = require('express'); const mongoose = require('mongoose'); const bcrypt = require('bcrypt'); const bodyParser = require('body-parser'); -const User = require('./user-model') +const User = require('./user-model'); +const StatsForUser = require("./stats-getter.js"); + +const statsGetter= new StatsForUser(); const app = express(); const port = 8001; +const cors = require('cors'); +app.use(cors()); + // Middleware to parse JSON in request body app.use(bodyParser.json()); @@ -45,6 +51,49 @@ app.post('/adduser', async (req, res) => { res.status(400).json({ error: error.message }); }}); + app.post("/userSaveGame", async (req, res) => { + try { + const { username, correctAnswers, incorrectAnswers, points, avgTime } = req.body; + + // Encontrar al usuario en la base de datos + const user = await User.findOne({ username }); + + if (!user) { + return res.status(404).json({ error: "Usuario no encontrado" }); + } + + // Crear un nuevo juego + const newGame = { + correctAnswers, + incorrectAnswers, + points, + avgTime + }; + + user.games.push(newGame); + + await user.save(); + + res.json({ message: "Partida guardada exitosamente" }); + } catch (error) { + res.status(400).json({ error: "Error al guardar partida"}); + } + }); + + app.get("/getstats", async (req, res) => { + const user = await User.findOne({ username:req.query.user }); + + if (!user) { + return res.status(404).json({ error: "Usuario no encontrado" }); + } + try { + var data = await statsGetter.getStatsForUser(req.query.user); + res.json(data); + } catch (error) { + res.status(400).json({ error: "Error al obtener las estadísticas" }); + } + }); + const server = app.listen(port, () => { console.log(`User Service listening at http://localhost:${port}`); }); diff --git a/webapp/src/App.js b/webapp/src/App.js index 36c1a324..b879f817 100644 --- a/webapp/src/App.js +++ b/webapp/src/App.js @@ -1,14 +1,13 @@ -import React, { useState } from 'react'; +import React from 'react'; import Authenticate from './pages/Authenticate/Authenticate.js'; import Home from './pages/Home/Home.js'; import Clasico from './pages/Clasico/Clasico.js'; import Bateria from './pages/Bateria/Bateria.js'; import WrongRoute from './pages/WrongRoute/WrongRoute.js'; +import Stats from './pages/Stats/Stats.js'; import './App.css'; import {BrowserRouter, Routes, Route, Navigate} from "react-router-dom"; -//Autentificamos que el usuario este registrado en la aplicación -//const [authenticated, setAuthenticated] = useState(false); function App() { return ( @@ -20,6 +19,7 @@ function App() { } /> } /> } /> + } /> {/* Ruta por defecto */} } /> @@ -28,4 +28,4 @@ function App() { ); } -export default App; \ No newline at end of file +export default App; diff --git a/webapp/src/components/Login/Login.js b/webapp/src/components/Login/Login.js index 46b2b5d8..6c89c8ee 100644 --- a/webapp/src/components/Login/Login.js +++ b/webapp/src/components/Login/Login.js @@ -19,11 +19,15 @@ const Login = () => { // Extract data from the response const { createdAt: userCreatedAt } = response.data; - + const { token: token } = response.data; setCreatedAt(userCreatedAt); setLoginSuccess(true); setOpenSnackbar(true); + localStorage.setItem('token', token); + + localStorage.setItem('username', username); + } catch (error) { setError(error.response.data.error); } diff --git a/webapp/src/components/Nav/Nav.js b/webapp/src/components/Nav/Nav.js index 95d8f951..59ec3610 100644 --- a/webapp/src/components/Nav/Nav.js +++ b/webapp/src/components/Nav/Nav.js @@ -9,6 +9,7 @@ const Nav = () => {
  • Home
  • Sobre nosotros
  • +
  • Stats
); diff --git a/webapp/src/components/Stats.js b/webapp/src/components/Stats.js new file mode 100644 index 00000000..34e2b0fd --- /dev/null +++ b/webapp/src/components/Stats.js @@ -0,0 +1,20 @@ +const axios = require('axios'); + +// Definir la función para realizar la solicitud +async function fetchStats() { + const username = localStorage.getItem('username'); + const url = 'http://localhost:8001/getstats'; + const params = { + user: username + }; + + try { + const response = await axios.get(url, { params }); + return response.data; + } catch (error) { + throw new Error('Error al obtener las estadísticas:', error); + } +} + +// Exportar la función +module.exports = { fetchStats }; \ No newline at end of file diff --git a/webapp/src/pages/Clasico/Clasico.js b/webapp/src/pages/Clasico/Clasico.js index 12c1f862..290d6d78 100644 --- a/webapp/src/pages/Clasico/Clasico.js +++ b/webapp/src/pages/Clasico/Clasico.js @@ -10,7 +10,7 @@ import axios from 'axios'; const JuegoPreguntas = () => { const [isLoading, setIsLoading] = useState(true); const [indicePregunta, setIndicePregunta] = useState(0); - const [puntuacion, setPuntuacion] = useState(0); + var [puntuacion, setPuntuacion] = useState(0); const [respuestaSeleccionada, setRespuestaSeleccionada] = useState(null); const [tiempoRestante, setTiempoRestante] = useState(10); const [juegoTerminado, setJuegoTerminado] = useState(false); @@ -73,7 +73,7 @@ const JuegoPreguntas = () => { const estiloRespuesta = (respuesta) => { if (preguntaTerminada) { - if (respuesta === preguntaActual.respuestaCorrecta) { + if (respuesta === preguntaActual.correcta) { return { backgroundColor: "#10FF00" }; } else if (respuesta === respuestaSeleccionada) { return { backgroundColor: "red" }; @@ -87,7 +87,7 @@ const JuegoPreguntas = () => { }; const handleSiguientePregunta = async () => { - if (respuestaSeleccionada === preguntaActual.respuestaCorrecta) { + if (respuestaSeleccionada === preguntaActual.correcta) { setPuntuacion(puntuacion + 1); setPreguntasCorrectas(preguntasCorrectas + 1); } else { @@ -104,40 +104,42 @@ const JuegoPreguntas = () => { setPreguntaActual(preguntas[indicePregunta]); } else { - if (preguntasCorrectas + preguntasFalladas > 0) { - setTiempoMedio(tiempoTotal/(preguntasCorrectas+preguntasFalladas)); - } - - //Now we store the game in the user's DB - const username = sessionStorage.getItem('username'); - const newGame = { - correctAnswers: preguntasCorrectas, - incorrectAnswers: preguntasFalladas, - points: puntuacion, - avgTime: tiempoMedio, - }; - try { - const response = await fetch('http://localhost:8004/saveGame', { + + if (preguntasCorrectas + preguntasFalladas > 0) { + setTiempoMedio(tiempoTotal/(preguntasCorrectas+preguntasFalladas)); + } + + //Now we store the game in the user's DB + const username = localStorage.getItem('username'); + const newGame = { + username: username, + correctAnswers: preguntasCorrectas, + incorrectAnswers: preguntasFalladas, + points: puntuacion, + avgTime: tiempoMedio, + }; + + const response = await fetch('http://localhost:8001/userSaveGame', { method: 'POST', headers: { 'Content-Type': 'application/json', }, - body: JSON.stringify({ - username, - game: newGame, - }), + body: JSON.stringify(newGame), }); if (!response.ok) { throw new Error('Error al guardar el juego'); } + } catch (error) { console.error('Error al guardar el juego:', error); // Manejar el error, por ejemplo, mostrando un mensaje al usuario } finally { setJuegoTerminado(true); } + + } }; @@ -149,6 +151,10 @@ const JuegoPreguntas = () => { setTiempoRestante(10); setJuegoTerminado(false); setMostrarMenu(false); + setPreguntasCorrectas(0); + setPreguntasFalladas(0); + setTiempoMedio(0); + setTiempoTotal(0); }; if (mostrarMenu) { diff --git a/webapp/src/pages/Stats/Stats.css b/webapp/src/pages/Stats/Stats.css new file mode 100644 index 00000000..355af678 --- /dev/null +++ b/webapp/src/pages/Stats/Stats.css @@ -0,0 +1,33 @@ +input, button, a{ + appearance: none; + background-color: transparent; + border: 0.13rem solid #0F0F0F; + border-radius: 15px; + box-sizing: border-box; + color: #0F0F0F; + padding: 1rem; + text-align: center; + text-decoration: none; + transition: all 300ms cubic-bezier(.23, 1, 0.32, 1); + user-select: none; + -webkit-user-select: none; + touch-action: manipulation; + width: 100%; + will-change: transform; + -webkit-box-shadow: 10px 10px 6px 0px rgba(0,255,192,1); + -moz-box-shadow: 10px 10px 6px 0px rgba(0,255,192,1); + box-shadow: 5px 5px 6px 0px rgba(0,255,192,1); + } + + strong { + font-size: 18px; + color: #6b456c; + font-family: "Times New Roman", serif; + +} + +body { + background-color: #ffffe5; + font-family: "Times New Roman", serif; + +} \ No newline at end of file diff --git a/webapp/src/pages/Stats/Stats.js b/webapp/src/pages/Stats/Stats.js new file mode 100644 index 00000000..2959c535 --- /dev/null +++ b/webapp/src/pages/Stats/Stats.js @@ -0,0 +1,117 @@ +import React, { useState, useEffect } from 'react'; +import axios from 'axios'; +import Nav from '../../components/Nav/Nav.js'; +import Footer from '../../components/Footer/Footer.js'; +import './Stats.css'; + + +const Stats = () => { + const [username, setUsername] = useState(localStorage.username); + const [stats, setStats] = useState(null); + const [isLoading, setIsLoading] = useState(true); + const [error, setError] = useState(null); + + + const fetchStats = () => { + setIsLoading(true); + fetch(`http://localhost:8001/getstats?user=${username}`) + .then((response) => response.json()) + .then((data) => { + setStats(data); + setIsLoading(false); + }) + .catch((error) => { + console.error('Error al obtener las preguntas:', error); + setError(error.message || 'Ha ocurrido un error al obtener las estadísticas'); + setIsLoading(false); + }); + }; + + useEffect(() => { + fetch(`http://localhost:8001/getstats?user=${username}`) + .then((response) => response.json()) + .then((data) => { + setStats(data); + setIsLoading(false); + }) + .catch((error) => { + console.error('Error al obtener las preguntas:', error); + setIsLoading(false); + }); + }, [username]); + + const handleUsernameChange = (event) => { + setUsername(event.target.value); + }; + + const handleSearch = () => { + if (username.trim() !== '') { + fetchStats(); + } + }; + + if (isLoading) { + return
+

Cargando ...

+

Se está consultando su búsqueda, espere unos instantes.

+
+ } + + if (error) { + return <> +