|
| 1 | +/* |
| 2 | +_____________________________________ |
| 3 | +https://github.com/kenysdev |
| 4 | +2024 - JavaScript |
| 5 | +_______________________________________ |
| 6 | +#20 PETICIONES HTTP |
| 7 | +--------------------------------------- |
| 8 | + * EJERCICIO: |
| 9 | + * Utilizando un mecanismo de peticiones HTTP de tu lenguaje, realiza |
| 10 | + * una petición a la web que tú quieras, verifica que dicha petición |
| 11 | + * fue exitosa y muestra por consola el contenido de la web. |
| 12 | + * |
| 13 | + * DIFICULTAD EXTRA (opcional): |
| 14 | + * Utilizando la PokéAPI (https://pokeapi.co), crea un programa por |
| 15 | + * terminal al que le puedas solicitar información de un Pokémon concreto |
| 16 | + * utilizando su nombre o número. |
| 17 | + * - Muestra el nombre, id, peso, altura y tipo(s) del Pokémon |
| 18 | + * - Muestra el nombre de su cadena de evoluciones |
| 19 | + * - Muestra los juegos en los que aparece |
| 20 | + * - Controla posibles errores |
| 21 | +*/ |
| 22 | +// ________________________________________________________ |
| 23 | + |
| 24 | +import fetch from "node-fetch"; |
| 25 | + |
| 26 | +async function getUser(userId) { |
| 27 | + try { |
| 28 | + const url = `https://jsonplaceholder.typicode.com/users/${userId}`; |
| 29 | + const response = await fetch(url); |
| 30 | + |
| 31 | + if (response.ok) { |
| 32 | + return await response.json(); |
| 33 | + } else { |
| 34 | + console.log(`Id: ${userId} no encontrado`); |
| 35 | + console.log("status_code: ", response.status); |
| 36 | + return {}; |
| 37 | + } |
| 38 | + } catch (error) { |
| 39 | + console.error("Error de conexión:", error.message); |
| 40 | + return {}; |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +function printUser(userData) { |
| 45 | + if (Object.keys(userData).length > 0) { |
| 46 | + console.log(`\nUsuario con id: '${userData.id}':\n` + |
| 47 | + `Nombre: ${userData.name}\n` + |
| 48 | + `Usuario: ${userData.username}\n` + |
| 49 | + `Email: ${userData.email}\n` + |
| 50 | + `Teléfono: ${userData.phone}`); |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +// ________________________________________________________ |
| 55 | +// DIFICULTAD EXTRA |
| 56 | + |
| 57 | +class GetPokemon { |
| 58 | + constructor() { |
| 59 | + this.baseUrl = "https://pokeapi.co/api/v2/pokemon/"; |
| 60 | + this.pokemon = null; |
| 61 | + } |
| 62 | + |
| 63 | + async load(id) { |
| 64 | + try { |
| 65 | + const url = `${this.baseUrl}${id}`; |
| 66 | + const response = await fetch(url); |
| 67 | + |
| 68 | + if (!response.ok) { |
| 69 | + throw new Error(`Pokémon '${id}' no encontrado (status: ${response.status})`); |
| 70 | + } |
| 71 | + |
| 72 | + this.pokemon = await response.json(); |
| 73 | + console.log(`\nPokémon '${id}' ha sido cargado.`); |
| 74 | + } catch (error) { |
| 75 | + GetPokemon.handleExceptions(error); |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + info() { |
| 80 | + if (!this.pokemon) { |
| 81 | + console.log("El Pokémon aún no ha sido cargado."); |
| 82 | + return; |
| 83 | + } |
| 84 | + |
| 85 | + console.log(`Información Básica \n` + |
| 86 | + `* Id: ${this.pokemon.id} \n` + |
| 87 | + `* Nombre: ${this.pokemon.name} \n` + |
| 88 | + `* Peso: ${this.pokemon.weight} kg \n` + |
| 89 | + `* Altura: ${this.pokemon.height} m \n` + |
| 90 | + `* Tipo(s):` |
| 91 | + ); |
| 92 | + |
| 93 | + this.pokemon.types.forEach((typeInfo) => { |
| 94 | + console.log(` - ${typeInfo.type.name}`);; |
| 95 | + }); |
| 96 | + } |
| 97 | + |
| 98 | + async evolutionChain() { |
| 99 | + if (!this.pokemon) { |
| 100 | + console.log("El Pokémon aún no ha sido cargado."); |
| 101 | + return; |
| 102 | + } |
| 103 | + |
| 104 | + try { |
| 105 | + const speciesUrl = this.pokemon.species.url; |
| 106 | + const speciesData = await fetch(speciesUrl).then((res) => res.json()); |
| 107 | + const evolutionChainUrl = speciesData.evolution_chain.url; |
| 108 | + const evolutionChainData = await fetch(evolutionChainUrl).then((res) => res.json()); |
| 109 | + |
| 110 | + console.log("\nCadena de evoluciones:"); |
| 111 | + let currentEvolution = evolutionChainData.chain; |
| 112 | + |
| 113 | + while (currentEvolution) { |
| 114 | + console.log(`- ${currentEvolution.species.name}`); |
| 115 | + currentEvolution = currentEvolution.evolves_to[0] || null; |
| 116 | + } |
| 117 | + } catch (error) { |
| 118 | + GetPokemon.handleExceptions(error); |
| 119 | + } |
| 120 | + } |
| 121 | + |
| 122 | + showGames() { |
| 123 | + if (!this.pokemon) { |
| 124 | + console.log("El Pokémon aún no ha sido cargado."); |
| 125 | + return; |
| 126 | + } |
| 127 | + |
| 128 | + console.log("\nJuegos en los que aparece:"); |
| 129 | + if (this.pokemon.game_indices.length > 0) { |
| 130 | + this.pokemon.game_indices.forEach((gameInfo) => { |
| 131 | + console.log(`- ${gameInfo.version.name}`); |
| 132 | + }); |
| 133 | + } else { |
| 134 | + console.log("No aparece en ninguno."); |
| 135 | + } |
| 136 | + } |
| 137 | + |
| 138 | + static handleExceptions(error) { |
| 139 | + if (error.name === "FetchError") { |
| 140 | + console.log("Error de conexión:", error.message); |
| 141 | + } else { |
| 142 | + console.log("Error inesperado:", error.message); |
| 143 | + } |
| 144 | + } |
| 145 | +} |
| 146 | + |
| 147 | +// ________________________________________________________ |
| 148 | +(async () => { |
| 149 | + const u1 = await getUser(1); |
| 150 | + printUser(u1); |
| 151 | + |
| 152 | + const u2 = await getUser(2); |
| 153 | + printUser(u2); |
| 154 | + |
| 155 | + const u3 = await getUser(777); // No existente. |
| 156 | + printUser(u3); |
| 157 | + |
| 158 | + console.log("\nDIFICULTAD EXTRA:"); |
| 159 | + |
| 160 | + try { |
| 161 | + const p1 = new GetPokemon(); |
| 162 | + await p1.load(1); |
| 163 | + p1.info(); |
| 164 | + await p1.evolutionChain(); |
| 165 | + p1.showGames(); |
| 166 | + |
| 167 | + const p2 = new GetPokemon(); |
| 168 | + await p2.load("ivysaur"); |
| 169 | + p2.info(); |
| 170 | + await p2.evolutionChain(); |
| 171 | + p2.showGames(); |
| 172 | + } catch (error) { |
| 173 | + GetPokemon.handleExceptions(error); |
| 174 | + } |
| 175 | +})(); |
0 commit comments