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

api.ts

94 lines2.4 KB

1import { queryOptions } from '@tanstack/react-query'
2​
3type Episode = {
4 id: number
5 name: string
6 air_date: string
7 episode: string
8 characters: Array<string>
9}
10​
11type Character = {
12 id: number
13 name: string
14 status: string
15 species: string
16 gender: string
17 origin: { name: string; url: string }
18 location: { name: string; url: string }
19 episode: Array<string>
21​
22type Location = {
23 id: number
24 name: string
25 type: string
27​
28type Paginated<T> = {
29 results: Array<T>
31​
32const getEpisodes = async (): Promise<Paginated<Episode>> => {
33 const res = await fetch('https://rickandmortyapi.com/api/episode/')
34 if (!res.ok) throw new Error('Failed to fetch episodes')
35 return await res.json()
37​
38const getEpisode = async (episodeId: string): Promise<Episode> => {
39 const res = await fetch(
40 `https://rickandmortyapi.com/api/episode/${episodeId}`,
41 )
42 if (!res.ok) throw new Error('Failed to fetch episode')
43 return await res.json()
45​
46const getCharacters = async (): Promise<Paginated<Character>> => {
47 const res = await fetch('https://rickandmortyapi.com/api/character/')
48 if (!res.ok) throw new Error('Failed to fetch characters')
49 return await res.json()
51​
52const getCharacter = async (characterId: string): Promise<Character> => {
53 const res = await fetch(
54 `https://rickandmortyapi.com/api/character/${characterId}`,
55 )
56 if (!res.ok) throw new Error('Failed to fetch character')
57 return await res.json()
59​
60const getLocation = async (locationId: string): Promise<Location> => {
61 const res = await fetch(
62 `https://rickandmortyapi.com/api/location/${locationId}`,
63 )
64 if (!res.ok) throw new Error('Failed to fetch location')
65 return await res.json()
67​
68export const episodesQueryOptions = queryOptions({
69 queryKey: ['episodes'],
70 queryFn: getEpisodes,
71})
72​
73export const episodeQueryOptions = (episodeId: string) =>
74 queryOptions({
75 queryKey: ['episode', episodeId],
76 queryFn: () => getEpisode(episodeId),
77 })
78​
79export const charactersQueryOptions = queryOptions({
80 queryKey: ['characters'],
81 queryFn: getCharacters,
82})
83​
84export const characterQueryOptions = (characterId: string) =>
85 queryOptions({
86 queryKey: ['character', characterId],
87 queryFn: () => getCharacter(characterId),
88 })
89​
90export const locationQueryOptions = (locationId: string) =>
91 queryOptions({
92 queryKey: ['location', locationId],
93 queryFn: () => getLocation(locationId),
94 })