Skip to content

Instantly share code, notes, and snippets.

@ulisesantana
Last active September 24, 2019 22:20
Show Gist options
  • Save ulisesantana/868ceb4e75ab52b3bb026c384644e6a0 to your computer and use it in GitHub Desktop.
Save ulisesantana/868ceb4e75ab52b3bb026c384644e6a0 to your computer and use it in GitHub Desktop.
Get all the pokemons from the PokeAPI and save it to a JSON file
{
"name": "saveAllPokemons",
"version": "0.0.1",
"main": "saveAllPokemons.js",
"scripts": {
"start": "node saveAllPokemons.js"
},
"dependencies": {
"axios": "^0.19.0"
},
"license": "MIT"
}
const {get} = require("axios");
const fs = require("fs");
(async () => {
try {
const pokemons = await getAllPokemons();
fs.writeFile('pokemons.json', JSON.stringify(pokemons, null, 2), (err) => {
if (err) throw err;
console.log('The pokemons have been saved!');
});
} catch (e) {
console.error('Error getting pokemons', e.toString())
}
})();
const getAllPokemons = async () => await processPage();
const processPage = (url = "https://pokeapi.co/api/v2/pokemon", cache = []) => new Promise((res, rej) => {
if (!!url) {
get(url)
.then(({data}) => {
if (data.next) {
console.log('Processing...', cache.length, 'processed.')
res(processPage(data.next, cache.concat(data.results.map(parsePokemon))));
} else {
res(cache.concat(data.results.map(parsePokemon)))
}
}).catch(e => {
console.error('Error getting page', e.toString());
rej(e)
})}
else {
return res(cache)
}
});
const parsePokemon = ({name, url}) => {
const [, id] = url.split('/').reverse();
return {
name: capitalize(name),
url,
id,
img: `https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${id}.png`
}
};
const capitalize = s => s.charAt(0).toUpperCase() + s.substring(1).toLowerCase();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment