forked from GeorgeCiesinski/poke-guesser-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pokemon.js
64 lines (59 loc) · 1.58 KB
/
pokemon.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/*
Functions that call PokéAPI
https://pokeapi.co/docs/v2
*/
function generatePokemon() {
// Fetch json of all available pokemon up to a limit of 2000 (~1200 avilable)
return fetch('https://pokeapi.co/api/v2/pokemon/?limit=2000')
// Parse to json
.then(res => {
return res.json();
})
// Extract results
.then(json => {
return json.results;
})
// Return random item from list
.then(resultList => {
return resultList[Math.floor(Math.random() * resultList.length)];
});
}
// Fetches the sprite using the pokemon's api url
function fetchSprite(url) {
return fetch(url)
// Converts result to json
.then(res => {
return res.json();
})
// returns the url of the sprite
.then(json => {
return json.sprites;
});
}
// Fetches the pokemon's names in different languages
function fetchNames(nameOrId) {
return fetch(`https://pokeapi.co/api/v2/pokemon-species/${nameOrId}/`)
// Parse to json
.then(res => res.json())
// Get names as array
.then(json => json.names)
// Format names
.then(names => {
let resultNames = [];
for (let i = 0; i < names.length; i++) {
resultNames.push({
languageName: names[i].language.name,
languageUrl: names[i].language.url,
name: names[i].name
});
}
return resultNames;
}).catch(err => {
// For example id 10220 gives back Not Found (404)
return null;
});
}
// Exports each function separately
module.exports.generatePokemon = generatePokemon;
module.exports.fetchSprite = fetchSprite;
module.exports.fetchNames = fetchNames;