Skip to content

Commit

Permalink
feat: provide boilerplate with lib
Browse files Browse the repository at this point in the history
  • Loading branch information
c-git committed Jan 4, 2025
1 parent 1acce7d commit 70ecf9f
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 26 deletions.
34 changes: 9 additions & 25 deletions examples/loop_yield_data_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
// the same. This example demonstrates how this crate can be used with the DataState type.

use anyhow::Context;
use reqwest::{Method, RequestBuilder, StatusCode};
use reqwest_cross::{fetch, reqwest, Awaiting, DataState};
use reqwest::Method;
use reqwest_cross::{fetch_plus, reqwest, Awaiting, DataState};

#[cfg(all(not(target_arch = "wasm32"), feature = "native-tokio"))]
#[tokio::main]
Expand Down Expand Up @@ -37,9 +37,14 @@ async fn common_code() -> Result<(), Box<dyn std::error::Error>> {
} else {
state.get(|| {
let req = client.request(Method::GET, "http://httpbin.org/get");
Awaiting(send_request_give_back_status(req, || {
let response_handler = |resp: reqwest::Result<reqwest::Response>| async {
resp.map(|resp| resp.status())
.context("Request failed, got an error back")
};
let ui_notify = || {
println!("Request Completed, this is where you would wake up your UI thread");
}))
};
Awaiting(fetch_plus(req, response_handler, ui_notify))

Check failure on line 47 in examples/loop_yield_data_state.rs

View workflow job for this annotation

GitHub Actions / Test WASM in browser

future cannot be sent between threads safely
});
reqwest_cross::yield_now().await;
}
Expand All @@ -48,28 +53,7 @@ async fn common_code() -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}

fn send_request_give_back_status<F>(
req: RequestBuilder,
ui_notify: F,
) -> reqwest_cross::oneshot::Receiver<anyhow::Result<StatusCode>>
where
F: FnOnce() + Send + 'static,
{
let (tx, rx) = reqwest_cross::oneshot::channel();
let on_done = move |resp: reqwest::Result<reqwest::Response>| async {
let status_code = resp
.map(|resp| resp.status())
.context("Request failed, got an error back");
tx.send(status_code).expect("failed to send oneshot msg");
ui_notify();
};
fetch(req, on_done);
println!("Request sent");
rx
}

#[cfg(all(test, not(target_arch = "wasm32")))]

mod tests {

#[tokio::test]
Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ mod wrappers;
mod yield_;

pub use data_state::{Awaiting, DataState, DataStateError, ErrorBounds};
pub use wrappers::fetch;
pub use wrappers::{fetch, fetch_plus};
#[cfg(feature = "yield_now")]
pub use yield_::yield_now;

Expand Down
28 changes: 28 additions & 0 deletions src/wrappers.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
//! Stores the wrapper functions that can be called from either native or wasm
//! code
use std::{fmt::Debug, future::Future};
use tracing::error;

#[cfg(not(target_arch = "wasm32"))]
/// Performs a HTTP requests and calls the given callback when done. NB: Needs
/// to use a callback to prevent blocking on the thread that initiates the
Expand Down Expand Up @@ -76,3 +79,28 @@ where
{
crate::wasm::spawn(future);
}

/// Wraps the call to fetch with the surrounding boilerplate
pub fn fetch_plus<FResponseHandler, FNotify, Fut, Ret>(
req: reqwest::RequestBuilder,
response_handler: FResponseHandler,
ui_notify: FNotify,
) -> crate::oneshot::Receiver<anyhow::Result<Ret>>
where
FResponseHandler: FnOnce(reqwest::Result<reqwest::Response>) -> Fut + Send + 'static,
Fut: Future<Output = anyhow::Result<Ret>> + Send,
Ret: Send + 'static,
Fut::Output: Debug,
FNotify: FnOnce() + Send + 'static,
{
let (tx, rx) = crate::oneshot::channel();
let on_done = move |resp: reqwest::Result<reqwest::Response>| async {
let output = response_handler(resp).await;
match tx.send(output) {
Ok(()) => ui_notify(),
Err(handler_output) => error!(?handler_output, "failed to send output from handler"),
};
};
fetch(req, on_done);
rx
}

0 comments on commit 70ecf9f

Please sign in to comment.