-
Notifications
You must be signed in to change notification settings - Fork 292
/
fetch.rs
167 lines (148 loc) · 4.74 KB
/
fetch.rs
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
use super::{ApiData, SomeSharedData};
use futures_util::future::Either;
use std::time::Duration;
use worker::{
wasm_bindgen_futures, AbortController, Delay, Env, Fetch, Method, Request, RequestInit,
Response, Result, RouteContext,
};
pub async fn handle_fetch(_req: Request, _env: Env, _data: SomeSharedData) -> Result<Response> {
let req = Request::new("https://example.com", Method::Post)?;
let resp = Fetch::Request(req).send().await?;
let resp2 = Fetch::Url("https://example.com".parse()?).send().await?;
Response::ok(format!(
"received responses with codes {} and {}",
resp.status_code(),
resp2.status_code()
))
}
#[worker::send]
pub async fn handle_fetch_json(
_req: Request,
_env: Env,
_data: SomeSharedData,
) -> Result<Response> {
let data: ApiData = Fetch::Url(
"https://jsonplaceholder.typicode.com/todos/1"
.parse()
.unwrap(),
)
.send()
.await?
.json()
.await?;
Response::ok(format!(
"API Returned user: {} with title: {} and completed: {}",
data.user_id, data.title, data.completed
))
}
pub async fn handle_proxy_request(
req: Request,
_env: Env,
_data: SomeSharedData,
) -> Result<Response> {
let uri = req.url()?;
let url = uri
.path_segments()
.unwrap()
.skip(1)
.collect::<Vec<_>>()
.join("/");
crate::console_log!("{}", url);
Fetch::Url(url.parse()?).send().await
}
pub async fn handle_request_init_fetch(
_req: Request,
_ctx: RouteContext<SomeSharedData>,
) -> Result<Response> {
let init = RequestInit::new();
Fetch::Request(Request::new_with_init("https://cloudflare.com", &init)?)
.send()
.await
}
pub async fn handle_request_init_fetch_post(
_req: Request,
_ctx: RouteContext<SomeSharedData>,
) -> Result<Response> {
let mut init = RequestInit::new();
init.method = Method::Post;
Fetch::Request(Request::new_with_init("https://httpbin.org/post", &init)?)
.send()
.await
}
pub async fn handle_cancelled_fetch(
_req: Request,
_ctx: RouteContext<SomeSharedData>,
) -> Result<Response> {
let controller = AbortController::default();
let signal = controller.signal();
let (tx, rx) = futures_channel::oneshot::channel();
// Spawns a future that'll make our fetch request and not block this function.
wasm_bindgen_futures::spawn_local({
async move {
let fetch = Fetch::Url("https://cloudflare.com".parse().unwrap());
let res = fetch.send_with_signal(&signal).await;
tx.send(res).unwrap();
}
});
// And then we try to abort that fetch as soon as we start it, hopefully before
// cloudflare.com responds.
controller.abort();
let res = rx.await.unwrap();
let res = res.unwrap_or_else(|err| {
let text = err.to_string();
Response::ok(text).unwrap()
});
Ok(res)
}
pub async fn handle_fetch_timeout(
_req: Request,
_ctx: RouteContext<SomeSharedData>,
) -> Result<Response> {
let controller = AbortController::default();
let signal = controller.signal();
let fetch_fut = async {
let fetch = Fetch::Url("https://miniflare.mocks/delay".parse().unwrap());
let mut res = fetch.send_with_signal(&signal).await?;
let text = res.text().await?;
Ok::<String, worker::Error>(text)
};
let delay_fut = async {
Delay::from(Duration::from_millis(100)).await;
controller.abort();
Response::ok("Cancelled")
};
futures_util::pin_mut!(fetch_fut);
futures_util::pin_mut!(delay_fut);
match futures_util::future::select(delay_fut, fetch_fut).await {
Either::Left((res, cancelled_fut)) => {
// Ensure that the cancelled future returns an AbortError.
match cancelled_fut.await {
Err(e) if e.to_string().contains("AbortError") => { /* Yay! It worked, let's do nothing to celebrate */
}
Err(e) => panic!(
"Fetch errored with a different error than expected: {:#?}",
e
),
Ok(text) => panic!("Fetch unexpectedly succeeded: {}", text),
}
res
}
Either::Right(_) => panic!("Delay future should have resolved first"),
}
}
pub async fn handle_cloned_fetch(
_req: Request,
_ctx: RouteContext<SomeSharedData>,
) -> Result<Response> {
let mut resp = Fetch::Url(
"https://jsonplaceholder.typicode.com/todos/1"
.parse()
.unwrap(),
)
.send()
.await?;
let mut resp1 = resp.cloned()?;
let left = resp.text().await?;
let right = resp1.text().await?;
Response::ok((left == right).to_string())
}