Last active
August 2, 2023 07:29
-
-
Save MikeyBeLike/6e43dc7b074eb84733cb59aae9fb4958 to your computer and use it in GitHub Desktop.
Normalise Pokemon API Data
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
promises as fs | |
} from 'fs' | |
import fetch from 'node-fetch' | |
const POKEMON_API_BASE_URL = 'https://pokeapi.co/api/v2' | |
function extractPokemonIdFromUrl(url) { | |
return new URL(url).pathname.split('/').at(-2) ?? '' | |
} | |
async function fetchAllPokemon() { | |
let url = `${POKEMON_API_BASE_URL}/pokemon?limit=2000` | |
const response = await fetch(url) | |
const data = await response.json() | |
let pokemonData = data.results; | |
// Fetch detailed data for each Pokémon | |
for (let i = 0; i < pokemonData.length; i++) { | |
const pokemon = pokemonData[i] | |
const pokemonResponse = await fetch(pokemon.url) | |
const pokemonDetailedData = await pokemonResponse.json() | |
// Fetch species data for each Pokémon to get the color and habitat | |
const speciesResponse = await fetch(pokemonDetailedData.species.url) | |
const speciesData = await speciesResponse.json() | |
// Include only the attributes we're interested in | |
pokemonData[i] = { | |
id: pokemonDetailedData.id, | |
name: pokemon.name, | |
weight: pokemonDetailedData.weight, | |
height: pokemonDetailedData.height, | |
image: `https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/${pokemonDetailedData.id}.png`, | |
color: speciesData.color ? { | |
id: Number(speciesData.color.url.split("/")[6]), | |
name: speciesData.color.name | |
} : null, | |
habitat: speciesData.habitat ? { | |
id: Number(extractPokemonIdFromUrl(speciesData.habitat.url)), | |
name: speciesData.habitat.name | |
} : null, | |
types: pokemonDetailedData.types.map(type => ({ | |
id: Number(extractPokemonIdFromUrl(type.type.url)), | |
name: type.type.name | |
})) | |
} | |
} | |
return pokemonData | |
} | |
fetchAllPokemon() | |
.then(data => { | |
fs.writeFile('pokemon_data.json', JSON.stringify(data, null, 2)) | |
.then(() => console.log('Pokemon data saved to pokemon_data.json')) | |
.catch(err => console.error('Error writing file:', err)) | |
}) | |
.catch(error => console.error('An error occurred:', error)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment