pokeapi-typescript
Version:
Typescript SDK for PokeAPI (https://pokeapi.co)
65 lines (64 loc) • 2.51 kB
JavaScript
import { Endpoint } from "./Endpoint.js";
const BASE_URI = "https://pokeapi.co/api/v2";
export class NamedEndpoint extends Endpoint {
_nameMap;
constructor(resource) {
super(resource);
this._nameMap = new Map();
}
get(param) {
return typeof param === "number" ? this.cache.get(param) : this.cache.get(this._nameMap.get(param.toLowerCase()) ?? 0);
}
async fetch(param, cache = true) {
const _param = typeof param === "string" ? param.toLowerCase() : param;
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 resolve(param) {
return this.get(param) ?? this.fetch(param);
}
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);
this._nameMap.set(data.name, data.id);
}
_isT(data) {
return "id" in data && "name" in data;
}
_isListT(data) {
return Array.isArray(data) && this._isT(data[0]);
}
}