-
Notifications
You must be signed in to change notification settings - Fork 0
/
pokemon.ts
49 lines (36 loc) · 1.22 KB
/
pokemon.ts
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
import crypto from "crypto";
import { assert } from "superstruct";
import { Pokemon } from "types";
export const specieEP = "https://pokeapi.co/api/v2/pokemon-species";
export const pokeEp = "https://pokeapi.co/api/v2/pokemon";
export const catchPokemon = async (id: number | string) => {
const specie = await fetch(`${specieEP}/${id}`);
const specieData = await specie.json();
const coin = crypto.randomBytes(1)[0];
const captureRate = Number(specieData?.capture_rate);
if (Number.isNaN(captureRate))
throw new Error("Capture rate is not a number");
return coin < captureRate;
};
export const fetchPokemon = async (id: number | string) => {
const [specie, poke] = await Promise.all([
fetch(`${specieEP}/${id}`),
fetch(`${pokeEp}/${id}`),
]);
const specieData = await specie.json();
const pokeData = await poke.json();
const data = {
id: pokeData?.id,
name: pokeData?.name,
order: pokeData?.order,
sprites: {
frontDefault: pokeData?.sprites?.front_default,
},
weight: pokeData?.weight,
height: pokeData?.height,
captureRate: specieData?.capture_rate,
description: specieData?.flavor_text_entries?.[0]?.flavor_text,
};
assert(data, Pokemon);
return data;
};