|
| 1 | +use super::{ApiData, SomeSharedData}; |
| 2 | +use futures_util::future::Either; |
| 3 | +use std::time::Duration; |
| 4 | +use worker::{ |
| 5 | + wasm_bindgen_futures, AbortController, Delay, Fetch, Method, Request, RequestInit, Response, |
| 6 | + Result, RouteContext, |
| 7 | +}; |
| 8 | + |
| 9 | +pub async fn handle_fetch(_req: Request, _ctx: RouteContext<SomeSharedData>) -> Result<Response> { |
| 10 | + let req = Request::new("https://example.com", Method::Post)?; |
| 11 | + worker::console_log!("foo"); |
| 12 | + let resp = Fetch::Request(req).send().await?; |
| 13 | + worker::console_log!("bar"); |
| 14 | + let resp2 = Fetch::Url("https://example.com".parse()?).send().await?; |
| 15 | + worker::console_log!("baz"); |
| 16 | + Response::ok(format!( |
| 17 | + "received responses with codes {} and {}", |
| 18 | + resp.status_code(), |
| 19 | + resp2.status_code() |
| 20 | + )) |
| 21 | +} |
| 22 | + |
| 23 | +pub async fn handle_fetch_json( |
| 24 | + _req: Request, |
| 25 | + _ctx: RouteContext<SomeSharedData>, |
| 26 | +) -> Result<Response> { |
| 27 | + let data: ApiData = Fetch::Url( |
| 28 | + "https://jsonplaceholder.typicode.com/todos/1" |
| 29 | + .parse() |
| 30 | + .unwrap(), |
| 31 | + ) |
| 32 | + .send() |
| 33 | + .await? |
| 34 | + .json() |
| 35 | + .await?; |
| 36 | + Response::ok(format!( |
| 37 | + "API Returned user: {} with title: {} and completed: {}", |
| 38 | + data.user_id, data.title, data.completed |
| 39 | + )) |
| 40 | +} |
| 41 | + |
| 42 | +pub async fn handle_proxy_request( |
| 43 | + _req: Request, |
| 44 | + ctx: RouteContext<SomeSharedData>, |
| 45 | +) -> Result<Response> { |
| 46 | + let url = ctx.param("url").unwrap(); |
| 47 | + Fetch::Url(url.parse()?).send().await |
| 48 | +} |
| 49 | + |
| 50 | +pub async fn handle_request_init_fetch( |
| 51 | + _req: Request, |
| 52 | + _ctx: RouteContext<SomeSharedData>, |
| 53 | +) -> Result<Response> { |
| 54 | + let init = RequestInit::new(); |
| 55 | + Fetch::Request(Request::new_with_init("https://cloudflare.com", &init)?) |
| 56 | + .send() |
| 57 | + .await |
| 58 | +} |
| 59 | + |
| 60 | +pub async fn handle_request_init_fetch_post( |
| 61 | + _req: Request, |
| 62 | + _ctx: RouteContext<SomeSharedData>, |
| 63 | +) -> Result<Response> { |
| 64 | + let mut init = RequestInit::new(); |
| 65 | + init.method = Method::Post; |
| 66 | + Fetch::Request(Request::new_with_init("https://httpbin.org/post", &init)?) |
| 67 | + .send() |
| 68 | + .await |
| 69 | +} |
| 70 | + |
| 71 | +pub async fn handle_cancelled_fetch( |
| 72 | + _req: Request, |
| 73 | + _ctx: RouteContext<SomeSharedData>, |
| 74 | +) -> Result<Response> { |
| 75 | + let controller = AbortController::default(); |
| 76 | + let signal = controller.signal(); |
| 77 | + |
| 78 | + let (tx, rx) = futures_channel::oneshot::channel(); |
| 79 | + |
| 80 | + // Spawns a future that'll make our fetch request and not block this function. |
| 81 | + wasm_bindgen_futures::spawn_local({ |
| 82 | + async move { |
| 83 | + let fetch = Fetch::Url("https://cloudflare.com".parse().unwrap()); |
| 84 | + let res = fetch.send_with_signal(&signal).await; |
| 85 | + tx.send(res).unwrap(); |
| 86 | + } |
| 87 | + }); |
| 88 | + |
| 89 | + // And then we try to abort that fetch as soon as we start it, hopefully before |
| 90 | + // cloudflare.com responds. |
| 91 | + controller.abort(); |
| 92 | + |
| 93 | + let res = rx.await.unwrap(); |
| 94 | + let res = res.unwrap_or_else(|err| { |
| 95 | + let text = err.to_string(); |
| 96 | + Response::ok(text).unwrap() |
| 97 | + }); |
| 98 | + |
| 99 | + Ok(res) |
| 100 | +} |
| 101 | + |
| 102 | +pub async fn handle_fetch_timeout( |
| 103 | + _req: Request, |
| 104 | + _ctx: RouteContext<SomeSharedData>, |
| 105 | +) -> Result<Response> { |
| 106 | + let controller = AbortController::default(); |
| 107 | + let signal = controller.signal(); |
| 108 | + |
| 109 | + let fetch_fut = async { |
| 110 | + let fetch = Fetch::Url("https://miniflare.mocks/delay".parse().unwrap()); |
| 111 | + let mut res = fetch.send_with_signal(&signal).await?; |
| 112 | + let text = res.text().await?; |
| 113 | + Ok::<String, worker::Error>(text) |
| 114 | + }; |
| 115 | + let delay_fut = async { |
| 116 | + Delay::from(Duration::from_millis(100)).await; |
| 117 | + controller.abort(); |
| 118 | + Response::ok("Cancelled") |
| 119 | + }; |
| 120 | + |
| 121 | + futures_util::pin_mut!(fetch_fut); |
| 122 | + futures_util::pin_mut!(delay_fut); |
| 123 | + |
| 124 | + match futures_util::future::select(delay_fut, fetch_fut).await { |
| 125 | + Either::Left((res, cancelled_fut)) => { |
| 126 | + // Ensure that the cancelled future returns an AbortError. |
| 127 | + match cancelled_fut.await { |
| 128 | + Err(e) if e.to_string().contains("AbortError") => { /* Yay! It worked, let's do nothing to celebrate */ |
| 129 | + } |
| 130 | + Err(e) => panic!( |
| 131 | + "Fetch errored with a different error than expected: {:#?}", |
| 132 | + e |
| 133 | + ), |
| 134 | + Ok(text) => panic!("Fetch unexpectedly succeeded: {}", text), |
| 135 | + } |
| 136 | + |
| 137 | + res |
| 138 | + } |
| 139 | + Either::Right(_) => panic!("Delay future should have resolved first"), |
| 140 | + } |
| 141 | +} |
| 142 | + |
| 143 | +pub async fn handle_cloned_fetch( |
| 144 | + _req: Request, |
| 145 | + _ctx: RouteContext<SomeSharedData>, |
| 146 | +) -> Result<Response> { |
| 147 | + let mut resp = Fetch::Url( |
| 148 | + "https://jsonplaceholder.typicode.com/todos/1" |
| 149 | + .parse() |
| 150 | + .unwrap(), |
| 151 | + ) |
| 152 | + .send() |
| 153 | + .await?; |
| 154 | + let mut resp1 = resp.cloned()?; |
| 155 | + |
| 156 | + let left = resp.text().await?; |
| 157 | + let right = resp1.text().await?; |
| 158 | + |
| 159 | + Response::ok((left == right).to_string()) |
| 160 | +} |
0 commit comments