pokeapi-typescript
Version:
Typescript SDK for PokeAPI (https://pokeapi.co)
66 lines (65 loc) • 2.31 kB
JavaScript
import { Collection } from "@discordjs/collection";
const BASE_URI = "https://pokeapi.co/api/v2";
class Endpoint {
resource;
_list;
cache;
constructor(resource) {
this.resource = resource;
this.cache = new Collection();
}
get(param) {
return this.cache.get(param);
}
async resolve(param) {
return this.get(param) ?? this.fetch(param);
}
async fetch(param, cache = true) {
const data = await fetch(`${BASE_URI}/${this.resource}/${param}`).then(async (res) => res.json());
if (!this._isT(data)) {
throw new Error(`Invalid data received from ${BASE_URI}/${this.resource}/${param}`);
}
this._cache(data);
return data;
}
async list(limit = 20, offset = 0) {
if (this._list) {
const results = this._list.results.slice(offset, limit);
const { count, next, previous } = this._list;
return { count, next, previous, results };
}
const params = new URLSearchParams({ limit: `${limit}`, offset: `${offset}` });
const data = await fetch(`${BASE_URI}/${this.resource}?${params}`).then(async (res) => res.json());
if (!this._isListT(data)) {
throw new Error(`Invalid data received from ${BASE_URI}/${this.resource}?${params}`);
}
return data;
}
async listAll(cache = true) {
if (this._list) {
return this._list;
}
const first = await fetch(`${BASE_URI}/${this.resource}?limit=1`).then(async (res) => res.json());
if (!this._isListT(first)) {
throw new Error(`Invalid data received from ${BASE_URI}/${this.resource}?limit=1`);
}
const data = await fetch(`${BASE_URI}/${this.resource}?limit=${first.count}`).then(async (res) => res.json());
if (!this._isListT(data)) {
throw new Error(`Invalid data received from ${BASE_URI}/${this.resource}?limit=${first.count}`);
}
if (cache) {
this._list = data;
}
return data;
}
_cache(data) {
this.cache.set(data.id, data);
}
_isT(data) {
return "id" in data;
}
_isListT(data) {
return Array.isArray(data) && this._isT(data[0]);
}
}
export { Endpoint };