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
pub use reqwasm::http::{Request, Response};
pub use wasm_bindgen::JsValue;

use serde::de::{Deserialize, DeserializeOwned, Deserializer};

use crate::error::{Error, ReqwasmResult, Result};

#[derive(Copy, Clone)]
pub struct MissingBody;

impl<'de> Deserialize<'de> for MissingBody {
    fn deserialize<D>(_deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        Ok(Self)
    }
}

#[derive(Default)]
pub struct JsonFetcher;

impl JsonFetcher {
    pub fn fetch<Body: 'static + DeserializeOwned>(
        request: Request,
        callback: impl FnOnce(Result<(Response, Result<Body>)>) + 'static,
    ) {
        wasm_bindgen_futures::spawn_local(async move {
            let result = fetch_success_json::<Body>(request).await;
            callback(result);
        });
    }

    pub fn send_get<Body: 'static + DeserializeOwned>(
        uri: impl AsRef<str>,
        callback: impl FnOnce(Result<(Response, Result<Body>)>) + 'static,
    ) {
        let request = Request::get(uri.as_ref());
        Self::fetch(request, callback);
    }

    pub fn send_post<Body: 'static + DeserializeOwned>(
        uri: impl AsRef<str>,
        body: impl Into<JsValue>,
        callback: impl FnOnce(Result<(Response, Result<Body>)>) + 'static,
    ) {
        let request = Request::post(uri.as_ref()).body(body);
        Self::fetch(request, callback);
    }

    pub fn send_post_json<Body: 'static + DeserializeOwned>(
        uri: impl AsRef<str>,
        body: impl Into<JsValue>,
        callback: impl FnOnce(Result<(Response, Result<Body>)>) + 'static,
    ) {
        let request = Request::post(uri.as_ref())
            .header("Content-Type", "application/json")
            .body(body);
        Self::fetch(request, callback);
    }
}

pub async fn fetch(request: Request) -> ReqwasmResult<Response> {
    request.send().await
}

pub async fn fetch_text(request: Request) -> ReqwasmResult<(Response, ReqwasmResult<String>)> {
    let response = request.send().await?;
    let body = response.text().await;
    Ok((response, body))
}

pub async fn fetch_json<Body: DeserializeOwned>(request: Request) -> ReqwasmResult<(Response, ReqwasmResult<Body>)> {
    let response = request.send().await?;
    let body = response.json().await;
    Ok((response, body))
}

pub async fn fetch_success(request: Request) -> Result<Response> {
    let response = request.send().await?;
    let status = response.status();

    if status == 200 {
        Ok(response)
    } else {
        Err(Error::FailureResponse(status, format!("{:?}", response.text().await)))
    }
}

pub async fn fetch_success_text(request: Request) -> Result<(Response, Result<String>)> {
    let response = request.send().await?;
    let body = response.text().await.map_err(Into::into);
    let status = response.status();

    if status == 200 {
        Ok((response, body))
    } else {
        Err(Error::FailureResponse(status, format!("{:?}", body)))
    }
}

pub async fn fetch_success_json<Body: DeserializeOwned>(request: Request) -> Result<(Response, Result<Body>)> {
    let response = request.send().await?;
    let status = response.status();

    if status == 200 {
        let body = response.json().await.map_err(Into::into);
        Ok((response, body))
    } else {
        Err(Error::FailureResponse(status, format!("{:?}", response.text().await)))
    }
}