1
//! Status-checked fetchers: a non-2xx response is an error carrying the
2
//! server's message, never a body to parse as success.
3

            
4
use wasm_bindgen::JsCast;
5
use wasm_bindgen::prelude::*;
6
use wasm_bindgen_futures::JsFuture;
7

            
8
use crate::escape::html_unescape;
9

            
10
/// The user-facing text of an error body: the JSON `message`, else the text
11
/// of an HTML fragment, else the bare status.
12
#[must_use]
13
4
pub fn error_message(status: u16, body: &str) -> String {
14
4
    let text = serde_json::from_str::<serde_json::Value>(body)
15
4
        .ok()
16
2
        .and_then(|json| json.get("message")?.as_str().map(str::to_owned))
17
3
        .unwrap_or_else(|| fragment_text(body));
18
4
    match text.trim() {
19
1
        "" => format!("HTTP {status}"),
20
3
        text => text.to_owned(),
21
    }
22
4
}
23

            
24
3
fn fragment_text(html: &str) -> String {
25
3
    let mut text = String::with_capacity(html.len());
26
3
    let mut in_tag = false;
27
3
    for c in html.chars() {
28
49
        match c {
29
2
            '<' => in_tag = true,
30
2
            '>' => in_tag = false,
31
45
            _ if !in_tag => text.push(c),
32
27
            _ => {}
33
        }
34
    }
35
3
    html_unescape(&text)
36
3
}
37

            
38
/// GETs `url`; `accept` sets the `Accept` header when given.
39
pub async fn fetch_get(url: &str, accept: Option<&str>) -> Result<String, JsValue> {
40
    let opts = web_sys::RequestInit::new();
41
    opts.set_method("GET");
42
    let headers = web_sys::Headers::new()?;
43
    if let Some(accept) = accept {
44
        headers.set("Accept", accept)?;
45
    }
46
    opts.set_headers(&headers);
47
    let request = web_sys::Request::new_with_str_and_init(url, &opts)?;
48
    let window = web_sys::window().ok_or("no window")?;
49
    let response: web_sys::Response = JsFuture::from(window.fetch_with_request(&request))
50
        .await?
51
        .dyn_into()?;
52
    let text = JsFuture::from(response.text()?)
53
        .await?
54
        .as_string()
55
        .ok_or("not a string")?;
56
    if response.ok() {
57
        Ok(text)
58
    } else {
59
        Err(JsValue::from_str(&error_message(response.status(), &text)))
60
    }
61
}
62

            
63
pub async fn fetch_json(url: &str) -> Result<String, JsValue> {
64
    fetch_get(url, Some("application/json")).await
65
}
66

            
67
#[cfg(test)]
68
mod tests;