Skip to content

Commit

Permalink
Only back testing left
Browse files Browse the repository at this point in the history
  • Loading branch information
Multichiki22 committed Jan 30, 2023
1 parent d2bf223 commit d3f3121
Show file tree
Hide file tree
Showing 57 changed files with 2,113 additions and 164 deletions.
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ build/Release
node_modules/
jspm_packages/


# TypeScript v1 declaration files
typings/

Expand Down Expand Up @@ -105,3 +106,7 @@ dist

# package-lock.json
package-lock.json
thunder-tests/thunderActivity.json
thunder-tests/thunderclient.json
thunder-tests/thunderCollection.json
thunder-tests/thunderEnvironment.json
57 changes: 31 additions & 26 deletions api/index.js
Original file line number Diff line number Diff line change
@@ -1,28 +1,33 @@
// _oo0oo_
// o8888888o
// 88" . "88
// (| -_- |)
// 0\ = /0
// ___/`---'\___
// .' \\| |// '.
// / \\||| : |||// \
// / _||||| -:- |||||- \
// | | \\\ - /// | |
// | \_| ''\---/'' |_/ |
// \ .-\__ '-' ___/-. /
// ___'. .' /--.--\ `. .'___
// ."" '< `.___\_<|>_/___.' >' "".
// | | : `- \`.;`\ _ /`;.`/ - ` : | |
// \ \ `_. \_ __\ /__ _/ .-` / /
// =====`-.____`.___ \_____/___.-`___.-'=====
// `=---='
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
const server = require('./src/app.js');
const { conn } = require('./src/db.js');
const server = require("./src/app.js");
const { sequelize } = require("./src/DB/db.js");
const PORT = 3000;
const { type } = require("./src/DB/DB");

// Syncing all the models at once.
conn.sync({ force: true }).then(() => {
server.listen(3001, () => {
console.log('%s listening at 3001'); // eslint-disable-line no-console
const preLoadTypes = async () => {
const url = "https://pokeapi.co/api/v2/type";

const types = await fetch(url)
.then((response) => response.json())
.then((data) => data)
.catch((error) => {
throw Error(error.message);
});

types.results.forEach((tipo) => {
type.findOrCreate({
where: { Nombre: tipo.name},
});
});
});
};

// Syncing all the models at once.
sequelize
.sync({ force: true })
.then(() => {
server.listen(PORT, () => {
preLoadTypes();
console.log(`Server listening on port ${PORT}`);
sequelize.sync({ force: true });
});
})
.catch((error) => console.log(error.message));
10 changes: 7 additions & 3 deletions api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
},
"dependencies": {
"body-parser": "^1.19.0",

"chai-http": "^4.3.0",

"cookie-parser": "^1.4.5",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
Expand All @@ -24,10 +27,11 @@
"sequelize": "^6.3.5"
},
"devDependencies": {
"supertest-session": "^4.1.0",
"mocha": "^8.2.1",
"chai": "^4.2.0",
"mocha": "^8.2.1",
"nodemon": "^2.0.6",
"supertest": "^6.0.1"
"supertest": "^6.0.1",
"supertest-as-promised": "^4.0.2",
"supertest-session": "^4.1.0"
}
}
219 changes: 219 additions & 0 deletions api/src/Controllers/Controllers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,219 @@
const { pokemon, type } = require("../DB/DB");

let idCreados = 0;

const traerPokemonsApi = async () => {
const links = [];
await fetch("https://pokeapi.co/api/v2/pokemon?offset=0&limit=40")
.then((response) => response.json())
.then((data) => {
data.results.map((pokemon) => {
links.push(pokemon["url"]);
});
})
.catch((error) => {
throw Error(error);
});

const promesas = links.map((url) => fetch(url));
const responses = await Promise.all(promesas);
const data = await Promise.all(responses.map((response) => response.json()));
// return data
return filtrarArrayApi(data);
};

const filtrarArrayApi = (arrayPokemones) => {
const infoRelevante = arrayPokemones.map((pokemon) =>
filtrarPokemonApi(pokemon)
);
return infoRelevante;
};

const filtrarPokemonApi = (pokemon, ruta = "Home") => {
const tipos = [];
pokemon["types"].forEach((element) => {
tipos.push(element["type"]["name"]);
});
let = pokemonFiltrado = {};
if (ruta === "Detail") {
pokemonFiltrado = {
ID: pokemon["id"],
Nombre: pokemon["name"],
Vida: pokemon["stats"][0]["base_stat"],
Ataque: pokemon["stats"][1]["base_stat"],
Defensa: pokemon["stats"][2]["base_stat"],
Velocidad: pokemon["stats"][5]["base_stat"],
Foto: pokemon["sprites"]["other"]["official-artwork"]["front_default"],
Altura: pokemon["height"],
Peso: pokemon["weight"],
Tipo: tipos,
};
} else {
pokemonFiltrado = {
ID: pokemon["id"],
Nombre: pokemon["name"],
Ataque: pokemon["stats"][1]["base_stat"],
Vida: pokemon["stats"][0]["base_stat"],
Defensa: pokemon["stats"][2]["base_stat"],
Velocidad: pokemon["stats"][5]["base_stat"],
Foto: pokemon["sprites"]["other"]["official-artwork"]["front_default"],
Tipo: tipos,
};
}

return pokemonFiltrado;
};

const traerPokemonsDB = async () => {
let PokemonsBD = await pokemon.findAll({
include: [
{
model: type,
attributes: ["Nombre"],
through: {
attributes: [],
},
},
],
});
const PokemonsBDcorregida = PokemonsBD.map((items) => items.dataValues);
PokemonsBDcorregida.map((pokemon) => {
filtrarPokemonBD(pokemon);
});
return PokemonsBDcorregida;
};

const filtrarPokemonBD = (pokemon) => {
const tipos = [];
pokemon.types.forEach((element) => tipos.push(element["Nombre"]));
pokemon["Tipo"] = tipos;
delete pokemon.types;
return pokemon;
};

const getPokemons = async () => {
const PokemonsBD = await traerPokemonsDB();
const PokemonsApi = await traerPokemonsApi();
//const PokemonsApi = []
const Pokemons = [...PokemonsBD, ...PokemonsApi];
return Pokemons;
};

const buscarPokemon = async (id) => {
if (id[0] == "C") {
const resultado = await pokemon.findOne({
where: { ID: id },
include: [
{
model: type,
attributes: ["Nombre"],
through: {
attributes: [],
},
},
],
}
);
if (resultado == null)
throw Error(`No se encontro el pokemon con id ${id}`);
return filtrarPokemonBD(resultado.dataValues);
} else {
const url = "https://pokeapi.co/api/v2/pokemon/" + id;
return await fetch(url)
.then((response) => response.json())
.then((pokemon) => {
return filtrarPokemonApi(pokemon, "Detail");
})
.catch((error) => {
throw Error(`No se encontro el pokemon con id ${id}`);
});
}
};

const buscarNombrePokemon = async (name) => {
const resultado = await pokemon.findAll({
where: { Nombre: name },
include: [
{
model: type,
attributes: ["Nombre"],
through: {
attributes: [],
},
},
],
});
if (resultado.length > 0) return filtrarPokemonBD(resultado[0].dataValues);
else {
const url = "https://pokeapi.co/api/v2/pokemon/" + name;
return await fetch(url)
.then((response) => response.json())
.then((pokemon) => {
return filtrarPokemonApi(pokemon);
})
.catch((error) => {
throw Error(`No se encontro el pokemon con Nombre ${name}`);
});
}
};

const traerTipos = async () => {
const resultados = await type.findAll();
return resultados;
};

const crearPokemon = async (
Nombre,
Vida,
Ataque,
Defensa,
Velocidad,
Altura,
Peso,
Tipo
) => {
if (Ataque === "")Ataque =null;
if (Vida === "") Vida = null;
if (Defensa === "") Defensa = null;
if (Velocidad === "") Velocidad = null;
if (Altura === "") Altura = null;
if (Peso === "") Peso = null;
const resultados = await pokemon.findAll({
where: {
Nombre: Nombre,
},
});
if (resultados.length != 0)
throw new Error("Ya existe un pokemon con ese nombre");
else if (!Nombre) throw Error("El pokemon debe tener un nombre");
const nuevoId = "C" + idCreados;
idCreados++;
const newPokemon = await pokemon.create({
ID: nuevoId,
Nombre,
Vida,
Ataque,
Defensa,
Velocidad,
Altura,
Peso,
});
Tipo.map(async (tipo) => {
const encontrado = await type.findOrCreate({
where: {
Nombre: tipo,
},
});
await newPokemon.addType(encontrado[0]);
});
return { ...newPokemon.dataValues, Tipo };
};

module.exports = {
getPokemons,
buscarNombrePokemon,
buscarPokemon,
traerTipos,
crearPokemon,
traerPokemonsApi,
};
30 changes: 30 additions & 0 deletions api/src/DB/DB.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
//importando los modelos de la carpeta models
const modelPokemon = require("./models/Pokemon");
const modelType = require("./models/Type");
const { Sequelize } = require("sequelize");
require("dotenv").config();

const { DB_USER, DB_PASSWORD, DB_HOST } = process.env;


const sequelize = new Sequelize(
`postgres://${DB_USER}:${DB_PASSWORD}@${DB_HOST}/pokemon`,
{
logging: false,
native: false,
}
);


modelPokemon(sequelize);
modelType(sequelize);


const { pokemon, type } = sequelize.models;


pokemon.belongsToMany(type, { through: "PokemonType" });
type.belongsToMany(pokemon, { through: "PokemonType" });

module.exports = {...sequelize.models, sequelize};

41 changes: 41 additions & 0 deletions api/src/DB/models/Pokemon.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
const { DataTypes } = require("sequelize");

module.exports = (DB) => {
DB.define(
"pokemon",
{
ID: {
type: DataTypes.STRING,
primaryKey: true,
unique: true,
allowNull: false,
},
Nombre: {
type: DataTypes.STRING,
unique: true,
allowNull: false,
},
Vida: {
type: DataTypes.FLOAT,
},
Ataque: {
type: DataTypes.FLOAT,
},
Defensa: {
type: DataTypes.FLOAT,
},
Velocidad: {
type: DataTypes.FLOAT,
},
Altura: {
type: DataTypes.FLOAT,
},
Peso: {
type: DataTypes.FLOAT,
},
},
{
timestamps: false,
}
);
};
Loading

0 comments on commit d3f3121

Please sign in to comment.