Last active
September 24, 2019 22:20
-
-
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
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
{ | |
"name": "saveAllPokemons", | |
"version": "0.0.1", | |
"main": "saveAllPokemons.js", | |
"scripts": { | |
"start": "node saveAllPokemons.js" | |
}, | |
"dependencies": { | |
"axios": "^0.19.0" | |
}, | |
"license": "MIT" | |
} |
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
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