sauron_core/dom/
http.rs

1//! provides functions for retrieving data using http network request
2use crate::dom::window;
3use js_sys::TypeError;
4use std::fmt::Debug;
5use wasm_bindgen::JsCast;
6use wasm_bindgen_futures::JsFuture;
7use web_sys::{RequestInit, Response};
8
9/// Provides functions for doing http network request
10#[derive(Copy, Clone, Debug)]
11pub struct Http;
12
13impl Http {
14    /// fetch text document from the url and decode the result with the supplied
15    pub async fn fetch_text(url: &str) -> Result<String, TypeError> {
16        let response = Self::fetch_with_request_init(url, None).await?;
17
18        let response_promise = response.text().expect("must be a promise text");
19
20        let response_text = JsFuture::from(response_promise)
21            .await
22            .expect("must not error")
23            .as_string()
24            .expect("must be a text");
25
26        Ok(response_text)
27    }
28
29    /// API for fetching http rest request
30    pub async fn fetch_with_request_init(
31        url: &str,
32        request_init: Option<RequestInit>,
33    ) -> Result<Response, TypeError> {
34        let fetch_promise = if let Some(ref request_init) = request_init {
35            window().fetch_with_str_and_init(url, request_init)
36        } else {
37            window().fetch_with_str(url)
38        };
39
40        match JsFuture::from(fetch_promise).await {
41            Ok(result) => {
42                let response: Response = result.unchecked_into();
43                Ok(response)
44            }
45            Err(err) => {
46                let type_error: TypeError = err.unchecked_into();
47                Err(type_error)
48            }
49        }
50    }
51}