-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.tsx
53 lines (39 loc) · 1.54 KB
/
index.tsx
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
import { PokemonResponse } from "./types/PokemonResponse";
import { PokemonsResponse } from "./types/PokemonsResponse";
import { renderToReadableStream } from "react-dom/server";
import Pokemon from "./components/Pokemon";
import PokemonList from "./components/PokemonList";
Bun.serve({
async fetch(request) {
const url = new URL(request.url);
if (url.pathname === "/pokemon") {
const response = await fetch("https://pokeapi.co/api/v2/pokemon");
const { results } = (await response.json()) as PokemonsResponse;
const stream = await renderToReadableStream(<PokemonList pokemon={results} />);
return new Response(stream, {
headers: { "Content-Type": "text/html" },
});
}
const pokemonNameRegex = /^\/pokemon\/([a-zA-Z0-9_-]+)$/;
const match = url.pathname.match(pokemonNameRegex);
if (match) {
const pokemonName = match[1];
const response = await fetch(`https://pokeapi.co/api/v2/pokemon/${pokemonName}`);
if (response.status === 404) {
return new Response("Not Found", { status: 404 });
}
const {
height,
name,
weight,
sprites: { front_default },
} = (await response.json()) as PokemonResponse;
const stream = await renderToReadableStream(<Pokemon name={name} height={height} weight={weight} img={front_default} />);
return new Response(stream, {
headers: { "Content-Type": "text/html" },
});
}
return new Response("Not Found", { status: 404 });
},
});
console.log("Listening ...");