Request

1import { Button, fetch, List, Markdown, Navigation, NavigationStack, Script, Section, Text, } from "scripting"
2
3function Example() {
4  return <NavigationStack>
5    <List
6      navigationTitle={"Request"}
7      navigationBarTitleDisplayMode={"inline"}
8    >
9      <Section
10        footer={
11          <Text>The fetch() method starts the process of fetching a resource from the network, returning a promise that is fulfilled once the response is available.</Text>
12        }
13      >
14        <Button
15          title={"fetch"}
16          action={async () => {
17            console.present()
18            console.log("Start fetching...")
19            try {
20              const html = await fetch(
21                "https://github.com"
22              ).then(
23                response => response.text()
24              )
25
26              if (html != null) {
27                const controller = new WebViewController()
28                controller.loadHTML(html, "https://github.com/")
29                await controller.present()
30                controller.dispose()
31              } else {
32                console.log("Failed to fetch the HTML content.")
33              }
34            } catch (e) {
35              console.error("Failed to fetch the HTML content, " + e)
36            }
37          }}
38        />
39      </Section>
40
41      <Section
42        footer={
43          <Text>Use a CancelToken object to cancel the request.</Text>
44        }
45      >
46        <Markdown
47          content={`\`\`\`ts
48const cancelToken = new CancelToken()
49fetch("https://example.com/api/data.json", {
50  cancelToken: cancelToken
51})
52.then(res => res.json())
53.then(data => {
54  // handle data
55})
56
57// Cancel the request after 2 seconds.
58setTimeout(() => {
59  cancelToken.cancel()
60}, 2000)
61\`\`\``}
62        />
63      </Section>
64
65      <Section
66        footer={
67          <Text>Options of the fetch() function</Text>
68        }
69      >
70        <Markdown
71          content={`\`\`\`ts
72fetch("https://example.com/api", {
73  method: "POST",
74  headers: {
75    "Content-Type": "application/json",
76  },
77  body: JSON.stringify(params),
78  connectTimeout: 5000, // 5 seconds
79  receiveTimeout: 10000, // 10 seconds
80  cancelToken: cancelToken, // CancelToken object
81})
82\`\`\`` }
83        />
84      </Section>
85
86      <Section
87        footer={
88          <Text>Get various data types based on different methods of the Response object</Text>
89        }
90      >
91        <Markdown
92          content={`\`\`\`ts
93const response = await fetch("https://example.com/api")
94
95response.text().then(text => {
96  // handle text content
97})
98
99response.json().then(jsonObject => {
100  // handle json data
101})
102
103response.arrayBuffer().then(arrayBuffer => {
104  // handle array buffer
105})
106\`\`\``}
107        />
108      </Section>
109
110      <Section
111        footer={
112          <Text>Programmatically reading and manipulating streams of data received over the network, chunk by chunk, is very useful</Text>
113        }
114      >
115        <Button
116          title={"Using readable streams for response"}
117          action={async () => {
118            console.present()
119
120            const response = await fetch(
121              "https://x.com",
122            )
123
124            const reader = response.body.getReader()
125
126            async function read() {
127              try {
128                while (true) {
129                  const {
130                    done,
131                    value
132                  } = await reader.read()
133
134                  if (done) {
135                    break
136                  } else if (value != null) {
137                    const text = value.toRawString()
138                    console.log("Received: " + text)
139                  }
140                }
141              } catch (e) {
142                console.error(String(e))
143              }
144            }
145
146            read()
147          }}
148        />
149      </Section>
150    </List>
151  </NavigationStack>
152}
153
154async function run() {
155  await Navigation.present({
156    element: <Example />
157  })
158
159  Script.exit()
160}
161
162run()