-
Notifications
You must be signed in to change notification settings - Fork 86
/
pokemon.handlers.mjs
97 lines (88 loc) · 2.64 KB
/
pokemon.handlers.mjs
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import axios from 'axios';
import { getCache, setCache } from '../utils/cache.mjs';
export const getPokemonEndpointResources = async (req, res, next) => {
try {
const { pokemonIdOrName } = req.params;
// Attempt to get all resources for the Pokémon endpoint from the cache
let pokemonEndpointResources = getCache('pokemonEndpointResources');
if (!pokemonEndpointResources) {
console.log(
'Fetching all resources for the Pokémon endpoint from PokéAPI'
);
const { data } = await axios.get(
`https://pokeapi.co/api/v2/pokemon/?limit=9000`
);
const { count, results } = data;
pokemonEndpointResources = {
count,
results: results.map(obj => {
const { name, url } = obj;
return {
id: Number(url.split('/').filter(Boolean).pop()),
name,
url: url.replace(
'https://pokeapi.co/api/v2/',
`${req.protocol}://${req.get('host')}/api/`
)
};
})
};
// Cache all Pokémon names and routes
setCache('pokemonEndpointResources', pokemonEndpointResources);
}
if (pokemonIdOrName) {
// User is requesting a specific Pokémon, so pass the data to the next middleware
// for id or name validation
res.locals.pokemonEndpointResources = pokemonEndpointResources;
next();
} else {
// User is requesting all Pokémon names and routes, so send the data as a response
res.send(pokemonEndpointResources);
}
} catch (err) {
next(err);
}
};
export const getPokemonData = async (req, res, next) => {
try {
const { pokemonIdOrName } = req.params;
console.log('Fetching Pokémon data from PokéAPI');
const { data } = await axios.get(
`https://pokeapi.co/api/v2/pokemon/${pokemonIdOrName}`
);
const {
base_experience,
height,
id,
name,
order,
sprites,
stats,
types,
weight
} = data;
// Remove unnecessary data for the required project
const simplifiedPokemonData = {
base_experience,
height,
id,
name,
order,
sprites: Object.keys(sprites)
.filter(key => typeof sprites[key] === 'string')
.reduce((obj, key) => {
obj[key] = sprites[key];
return obj;
}, {}),
stats,
types,
weight
};
// Cache simplified data by id and name, then send it as a response
setCache(simplifiedPokemonData.id, simplifiedPokemonData);
setCache(simplifiedPokemonData.name, simplifiedPokemonData);
res.send(simplifiedPokemonData);
} catch (err) {
next(err);
}
};