Skip to content

Commit

Permalink
Use web-sys instead of ureq to make requests.
Browse files Browse the repository at this point in the history
  • Loading branch information
01mf02 committed Mar 14, 2024
1 parent 2393c0e commit b7a4976
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 89 deletions.
86 changes: 1 addition & 85 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion koweb/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ console_log = { version = "1.0", features = ["color"] }
error-chain = { version = "0.12.4", default-features = false }
getrandom = { version = "0.2.3", features = ["js"] }
log = "0.4.6"
ureq = { version = "2.9", default-features = false }
serde = { version = "1.0", features = ["derive"] }
serde-wasm-bindgen = "0.4"
wasm-bindgen = { version = "0.2", features = ["serde-serialize"] }
wasm-bindgen-futures = "0.4.23"
web-sys = { version = "0.3.4", features = ["Response", "Window"] }
26 changes: 23 additions & 3 deletions koweb/src/fetch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,31 @@ use error_chain::error_chain;
error_chain! {
foreign_links {
Io(std::io::Error);
Ureq(ureq::Error);
}
}

// TODO: remove async
pub async fn fetch(url: &str) -> Result<String> {
Ok(ureq::get(url).call()?.into_string()?)
log::info!("Fetching {url} ...");
// TODO: handle errors
Ok(run(url).await.unwrap())
}

use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use wasm_bindgen_futures::JsFuture;
use web_sys::Response;

// Adapted from: https://rustwasm.github.io/wasm-bindgen/examples/fetch.html
pub async fn run(url: &str) -> core::result::Result<String, JsValue> {
let window = web_sys::window().unwrap();
let resp_value = JsFuture::from(window.fetch_with_str(&url)).await?;

// `resp_value` is a `Response` object.
assert!(resp_value.is_instance_of::<Response>());
let resp: Response = resp_value.dyn_into().unwrap();

// Convert this other `Promise` into a rust `Future`.
let json = JsFuture::from(resp.text()?).await?;

Ok(json.as_string().unwrap())
}

0 comments on commit b7a4976

Please sign in to comment.