/
swapi-example.ts
44 lines (39 loc) · 1.23 KB
/
swapi-example.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
import { createTypeLevelClient, initUntypeable } from "../../src/index";
import { Person, Paginated, Planet, Film, Vehicle } from "./types";
const u = initUntypeable();
/**
* Create the router
*/
const router = u.router({
"/people/:id": u.input<{ id: string }>().output<Person>(),
"/people": u.output<Paginated<Person>>(),
"/planets/:id": u.input<{ id: string }>().output<Planet>(),
"/planets": u.output<Paginated<Planet>>(),
"/films/:id": u.input<{ id: string }>().output<Film>(),
"/films": u.output<Paginated<Film>>(),
"/vehicles/:id": u.input<{ id: string }>().output<Vehicle>(),
"/vehicles": u.output<Paginated<Vehicle>>(),
});
/**
* Create the client, using the zero-bundle method
*/
export const fetchFromSwapi = createTypeLevelClient<typeof router>(
(path, input = {}) => {
// Replace dynamic path params in url
const pathWithParams = path.replace(
/:([a-zA-Z0-9_]+)/g,
(_, key) => input[key],
);
return fetch(`https://swapi.dev/api${pathWithParams}`, {
method: "GET",
headers: {
"Content-Type": "application/json",
},
}).then((res) => {
if (!res.ok) {
throw new Error(`HTTP error! status: ${res.status}`);
}
return res.json();
});
},
);