Skip to content

Commit

Permalink
Nico nedb
Browse files Browse the repository at this point in the history
  • Loading branch information
NicoRedondoo committed Mar 10, 2024
1 parent ae26ce4 commit 0d0d3ab
Show file tree
Hide file tree
Showing 3 changed files with 175 additions and 93 deletions.
232 changes: 156 additions & 76 deletions Nico/index-api.js
Original file line number Diff line number Diff line change
@@ -1,49 +1,95 @@
const { ufc_data, calcularMediaTiempoPelea } = require("./index-NRM");
const {ufc_data} = require("./index-NRM");
const API_BASE = "/api/v1";



function api_NRM(app) {
module.exports = (app, dbUfc) => {

let dataset = [];


// CREAR initial data
app.get(API_BASE+"/ufc-events-data/loadInitialData", (req, res) => {
if (dataset.length === 0) {
for (let i = 0; i < ufc_data.length; i++) {
const fields = ufc_data[i].split('\t');
const obj = {
location: fields[0],
fighter1: fields[1],
fighter2: fields[2],
fighter_1_kd: parseFloat(fields[3]),
fighter_2_kd: parseFloat(fields[4]),
fighter_1_str: parseFloat(fields[5]),
fighter_2_str: parseFloat(fields[6]),
fighter_1_td: parseFloat(fields[7]),
fighter_2_td: parseFloat(fields[8]),
fighter_1_sub: parseFloat(fields[9]),
fighter_2_sub: parseFloat(fields[10]),
weight_class: fields[11],
method: fields[12],
round: parseFloat(fields[13]),
time: fields[14],
event_name: fields[15],
date: fields[16],
winner: fields[17]
};
dataset.push(obj);
dbUfc.find({}, (err, docs) => {
if (err) {
res.sendStatus(500, 'Internal Error');
} else {
if (docs.length === 0) {
for (let i = 0; i < ufc_data.length; i++) {
const fields = ufc_data[i].split('\t');
const obj = {
location: fields[0],
fighter1: fields[1],
fighter2: fields[2],
fighter_1_kd: parseFloat(fields[3]),
fighter_2_kd: parseFloat(fields[4]),
fighter_1_str: parseFloat(fields[5]),
fighter_2_str: parseFloat(fields[6]),
fighter_1_td: parseFloat(fields[7]),
fighter_2_td: parseFloat(fields[8]),
fighter_1_sub: parseFloat(fields[9]),
fighter_2_sub: parseFloat(fields[10]),
weight_class: fields[11],
method: fields[12],
round: parseFloat(fields[13]),
time: fields[14],
event_name: fields[15],
date: fields[16],
winner: fields[17]
}
dbUfc.insert(obj);

}
res.sendStatus(201, "Created");
} else {
res.sendStatus(409, 'Conflict');
}
}
res.send(dataset); // Enviar dataset como array de objetos
res.sendStatus(201);
} else {
res.sendStatus(409);
}
});
});
});

// GET Base
app.get(API_BASE+"/ufc-events-data", (req, res) => {
res.status(200).json(dataset);
dbUfc.find({}, (err, events) => {
if (err) {
res.sendStatus(500, 'Internal Error');
} else {
// Consultas con parámetros
if (!(Object.keys(req.query).length === 0)) {

if (req.query.limit && req.query.offset) {
let limit = parseInt(req.query.limit);
let offset = parseInt(req.query.offset);
res.send(JSON.stringify(events.slice(offset, limit)));
} else if(req.query.limit && !req.query.offset){
let limit = parseInt(req.query.limit);
res.send(JSON.stringify(events.slice(0, limit)));
} else if (!req.query.limit && req.query.offset) {
let offset = parseInt(req.query.offset);
res.send(JSON.stringify(events.slice(offset)));
} else {
let mostrar = []
let queryParams = Object.keys(req.query);
for (let i = 0; i < events.length; i++) {
let match = true;
for (let j = 0; j < queryParams.length; j++) {
if (events[i][queryParams[j]] !== req.query[queryParams[j]]) {
match = false;
break;
}
}
if (match) {
mostrar.push(events[i]);
}
}
res.send(JSON.stringify(mostrar));
}
// Consultas sin parámetros
} else {
res.send(JSON.stringify(events));
}
}
})
});

// POST Nuevo evento
Expand All @@ -65,28 +111,46 @@ function api_NRM(app) {
return res.status(400).send('Incorrect JSON');
}
// Verificar si ya existe un evento con los mismos luchadores y fecha
const exists = dataset.some(obj => obj.fighter1 === fight.fighter1 && obj.fighter2 === fight.fighter2 && obj.date === fight.date);
if (exists) {
return res.status(409).send('Conflict');
}
// Agregar el nuevo evento al dataset
dataset.push(fight);
return res.status(201).send('Created');
dbUfc.findOne({fighter1: fight.fighter1, fighter2: fight.fighter2, date: fight.date}, (err, existingFight) => {
if (err) {
return res.status(500).send('Internal Error');
}

if (existingFight) {
return res.status(409).send('Conflict');
}
dbUfc.insert(fight, (err, newFight) => {
if (err) {
return res.status(500).send('Internal Error');
} else {
return res.status(201).send('Created');
}
});
});
});




// DELETE de todo
app.delete(API_BASE+"/ufc-events-data", (req, res) => {
if (dataset.length === 0) {
return res.sendStatus(404, 'No data found to delete');
} else {
while (dataset.length > 0) {
dataset.pop();
dbUfc.find({}, (err, dat) => {
if (err) {
res.sendStatus(500, "Internal Error");
} else {
if (dat.length === 0) {
res.sendStatus(404, 'No data found to delete.')
} else {
dbUfc.remove({}, {multi: true}, (err, removed) => {
if (err) {
res.sendStatus(500, "Internal Error");
} else {
res.status(200).send(`OK, ${removed} data deleted.`)
}
});
}
}
return res.sendStatus(200, 'OK');
}
});
});

// 16.4 GET Rec inexistente
Expand All @@ -102,14 +166,18 @@ app.delete(API_BASE+"/ufc-events-data", (req, res) => {
// GET del recurso especificado
app.get(API_BASE+"/ufc-events-data/:peso", (req, res) => {
const peso = req.params.peso;
const datosFiltrados = dataset.filter(obj => obj.weight_class === peso);

if (datosFiltrados.length === 0) {
res.sendStatus(404,"Not Found");
} else {
res.send(JSON.stringify(datosFiltrados));
res.sendStatus(200,"OK");
}
dbUfc.find({weight_class: peso}, (err, datosFiltrados) => {
if (err) {
res.sendStatus(500, "Internal Error");
} else {
if (datosFiltrados.length === 0) {
res.sendStatus(404, "Not Found");
} else {
res.send(JSON.stringify(datosFiltrados));
}
}
})
});

// POST No permitido en un recurso
Expand All @@ -130,34 +198,46 @@ app.delete(API_BASE+"/ufc-events-data", (req, res) => {
return;
}

// const identificador = `${f1}:${f2}:${fdate}`;

const index = dataset.findIndex(item => {
return (
item.fighter1 === f1 &&
item.fighter2 === f2 &&
item.date === fdate
);
});
if (index !== -1) {
Object.assign(dataset[index], sw);
res.sendStatus(200, 'OK');
} else {
res.sendStatus(400, "Bad Request");
}
dbUfc.update(
{fighter1: f1, fighter2: f2, date: fdate},
{ $set: sw},
{},
(err, affected) => {
if (err) {
res.status(500).send('Internal Error');
} else {
if (affected === 1) {
res.status(200).send("OK");
} else {
res.status(404).send("Not Found");
}
}
}
)
});

// DELETE El recurso peso
app.delete(API_BASE+"/ufc-events-data/:peso", (req, res) => {
const peso = req.params.peso;

if (dataset.find(obj => obj.weight_class === peso)) {
dataset = dataset.filter(obj => obj.weight_class !== peso);
res.sendStatus(200, "OK");
} else {
res.sendStatus(404, "Not Found");
}
dbUfc.remove({weight_class: peso}, { multi: true}, (err, removed) => {

if (err) {
return res.sendStatus(500, "Internal Error");
} else {
if (removed >= 1) {
return res.sendStatus(200, `OK, ${removed} data removed.`);
} else {
return res.sendStatus(404, "Not Found");
}
}
})
});


//Documentación Postman
app.get(API_BASE + "/ufc-events-data/docs", (req, res) => {
res.status(301).redirect("https://documenter.getpostman.com/view/32992444/2sA2xh3tEg")
});

}
module.exports = api_NRM;
34 changes: 18 additions & 16 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@ let calcularMediaTiempoPelea = require('./Nico/index-NRM');
let enriqueAPI = require("./Enrique/index");
let api_VEG = require('./Victor/api-VEG');
let api_NRM = require('./Nico/index-api');
const data = require("./Victor/index-VEG");

let dbMovies = new dataStore();
let db = new dataStore();
let dbUfc = new dataStore();


let app = express();
Expand All @@ -33,29 +35,29 @@ app.listen(PORT,()=>{
// });

// Nicolas Redondo Moreno
app.get("/samples/NRM", (req, res) => {
const {mediaMinu, mediaSeg} = calcularMediaTiempoPelea();
console.log("mediaMinu:", mediaMinu);
console.log("mediaSeg:", mediaSeg);
const htmlResponse = `
<html>
<body>
<h1>Resultado de los datos de Nico</h1>
<h3>La media de tiempo de las peleas del dataset es de ${mediaMinu} minutos y ${mediaSeg} segundos.</h3>
</body>
</html>`;
res.send(htmlResponse);
});
// app.get("/samples/NRM", (req, res) => {
// const {mediaMinu, mediaSeg} = calcularMediaTiempoPelea();
// console.log("mediaMinu:", mediaMinu);
// console.log("mediaSeg:", mediaSeg);
// const htmlResponse = `
// <html>
// <body>
// <h1>Resultado de los datos de Nico</h1>
// <h3>La media de tiempo de las peleas del dataset es de ${mediaMinu} minutos y ${mediaSeg} segundos.</h3>
// </body>
// </html>`;
// res.send(htmlResponse);
// });

api_NRM(app);
api_NRM(app, dbUfc);

//Enrique Garcia Olivares
enriqueAPI(app, dbMovies);

// Elimidada la ruta /samples/EGO
// app.get("/samples/EGO", (req, res) => {
// let paisFiltro = "United States of America"
// let presupuestoMedioPais = presupuesto(paisFiltro)
// let paisFiltro = "United States of America"
// let presupuestoMedioPais = presupuesto(paisFiltro)
// res.send(`<html><body><h2>El presupuesto medio de las peliculas producidas en ${paisFiltro} es de ${presupuestoMedioPais}€</h2></body></html>`)
// })

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"start": "node index.js",
"test": "npm run test-EGO && npm run test-NRM && npm run test-VEG",
"test-EGO": "npx newman run ./Enrique/tests/CollectionAPIEGO.json -e ./Enrique/tests/enviroments/GCloudEnv.json",
"test-NRM": "npx newman run ./tests/apiNRM-gcloud.json -e ./tests/enviroments/gcloud.json",
"test-NRM": "npx newman run ./tests/apiNRM-gcloud.json",
"test-VEG": "npx newman run ./tests/apiVEG-gcloud.json -e ./tests/enviroments/gcloud.json"
},
"dependencies": {
Expand Down

0 comments on commit 0d0d3ab

Please sign in to comment.