PokemonStore for a shared pokemon cache

This commit is contained in:
Daniel Odendahl Jr
2018-08-29 20:49:23 +00:00
parent dbcb80a7b5
commit 632cea6ec5
6 changed files with 80 additions and 69 deletions
+21
View File
@@ -0,0 +1,21 @@
const { Collection } = require('discord.js');
const request = require('node-superfetch');
const Pokemon = require('./Pokemon');
module.exports = class PokemonStore extends Collection {
constructor(iterable) {
super(iterable);
}
async fetch(query) {
query = encodeURIComponent(query.toLowerCase().replace(/ /g, '-').replace(/[^a-zA-Z0-9-]/g, ''));
const num = Number.parseInt(query, 10);
if (this.has(num)) return this.get(num);
const found = this.find(pokemon => pokemon.slug === query);
if (found) return found;
const { body } = await request.get(`https://pokeapi.co/api/v2/pokemon-species/${query}/`);
const pokemon = new Pokemon(body);
this.set(pokemon.id, pokemon);
return pokemon;
}
};