|
| 1 | +import z from 'zod' |
1 | 2 | // import { fakeFetch } from './utils' |
2 | 3 |
|
3 | 4 | /**************************************** |
4 | | - Part One: Request |
| 5 | + Part 1: Request |
5 | 6 | *****************************************/ |
6 | 7 |
|
7 | | -function getPersonVehicles(id: number) { |
8 | | - fetch(`https://swapi.dev/api/people/${id}`).then(() => { |
9 | | - console.log('Promise is resolved') |
10 | | - }) |
11 | | -} |
| 8 | +// function getPerson(id: number) { |
| 9 | +// fetch(`https://swapi.dev/api/people/${id}`).then(() => { |
| 10 | +// console.log('Promise is resolved') |
| 11 | +// }) |
| 12 | +// } |
12 | 13 |
|
13 | | -getPersonVehicles(1) |
| 14 | +// getPerson(1) |
14 | 15 |
|
15 | 16 | /**************************************** |
16 | | - Part Two: Response |
| 17 | + Part 2: Response |
17 | 18 | *****************************************/ |
18 | 19 |
|
19 | 20 | // Docs: "[fetch] resolves to the Response object representing the response to your request." |
20 | 21 | // https://developer.mozilla.org/en-US/docs/Web/API/fetch#return_value |
21 | 22 |
|
22 | | -// function getPersonVehicles(id: number) { |
23 | | -// fetch(`https://swapi.dev/api/people/${id}`).then((stuff) => { |
24 | | -// console.log('What is this', stuff) |
| 23 | +// function getPerson(id: number) { |
| 24 | +// fetch(`https://swapi.dev/api/people/${id}`).then((res) => { |
| 25 | +// console.log('What is in the response', res) |
25 | 26 | // }) |
26 | 27 | // } |
27 | 28 |
|
28 | | -// getPersonVehicles(1) |
| 29 | +// getPerson(1) |
29 | 30 |
|
30 | 31 | /**************************************** |
31 | | - Custom Fetch |
| 32 | + Part 3: Custom Fetch |
32 | 33 | *****************************************/ |
33 | 34 |
|
34 | 35 | // fakeFetch('fake-api') |
35 | 36 | // .then((res) => res.json()) |
36 | 37 | // .then((data) => { |
37 | 38 | // console.log(data) |
38 | 39 | // }) |
| 40 | + |
| 41 | +/**************************************** |
| 42 | + Part 4: Typesafe Network Response |
| 43 | +*****************************************/ |
| 44 | + |
| 45 | +// const personSchema = z.object({ |
| 46 | +// name: z.string(), |
| 47 | +// height: z.string().transform((val) => Number(val)), |
| 48 | +// }) |
| 49 | + |
| 50 | +// type Person = z.infer<typeof personSchema> |
| 51 | + |
| 52 | +type Person = { |
| 53 | + name: string |
| 54 | + height: number |
| 55 | +} |
| 56 | + |
| 57 | +function getPerson(id: number) { |
| 58 | + return fetch(`https://swapi.dev/api/people/${id}`) |
| 59 | + .then((res) => res.json()) |
| 60 | + .then((data) => { |
| 61 | + return data as Person |
| 62 | + }) |
| 63 | +} |
| 64 | + |
| 65 | +getPerson(1).then((person) => { |
| 66 | + console.log(person) |
| 67 | +}) |
0 commit comments