Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

api.ts

88 lines2.2 KB

1import { queryOptions, skipToken } from '@tanstack/react-query'
2​
3type Film = {
4 title: string
5 episode_id: number
6 opening_crawl: string
7 release_date: string
8 characters: Array<string>
9 url: string
11​
12type Character = {
13 name: string
14 height: string
15 mass: string
16 hair_color: string
17 eye_color: string
18 birth_year: string
19 homeworld: string
20 films: Array<string>
21 url: string
23​
24type Planet = {
25 name: string
27​
28type Paginated<T> = {
29 results: Array<T>
31​
32const getFilms = async (): Promise<Paginated<Film>> => {
33 const res = await fetch('https://swapi.dev/api/films/')
34 if (!res.ok) throw new Error('Failed to fetch films')
35 return await res.json()
37​
38const getFilm = async (filmId: string): Promise<Film> => {
39 const res = await fetch(`https://swapi.dev/api/films/${filmId}/`)
40 if (!res.ok) throw new Error('Failed to fetch film')
41 return await res.json()
43​
44const getCharacters = async (): Promise<Paginated<Character>> => {
45 const res = await fetch('https://swapi.dev/api/people/')
46 if (!res.ok) throw new Error('Failed to fetch characters')
47 return await res.json()
49​
50const getCharacter = async (characterId: string): Promise<Character> => {
51 const res = await fetch(`https://swapi.dev/api/people/${characterId}/`)
52 if (!res.ok) throw new Error('Failed to fetch character')
53 return await res.json()
55​
56const getPlanet = async (planetId: string): Promise<Planet> => {
57 const res = await fetch(`https://swapi.dev/api/planets/${planetId}/`)
58 if (!res.ok) throw new Error('Failed to fetch planet')
59 return await res.json()
61​
62export const filmsQueryOptions = queryOptions({
63 queryKey: ['films'],
64 queryFn: getFilms,
65})
66​
67export const filmQueryOptions = (filmId: string | undefined) =>
68 queryOptions({
69 queryKey: ['film', filmId],
70 queryFn: filmId ? () => getFilm(filmId) : skipToken,
71 })
72​
73export const charactersQueryOptions = queryOptions({
74 queryKey: ['characters'],
75 queryFn: getCharacters,
76})
77​
78export const characterQueryOptions = (characterId: string) =>
79 queryOptions({
80 queryKey: ['character', characterId],
81 queryFn: () => getCharacter(characterId),
82 })
83​
84export const homeworldQueryOptions = (homeworldId: string) =>
85 queryOptions({
86 queryKey: ['homeworld', homeworldId],
87 queryFn: () => getPlanet(homeworldId),
88 })