Lines
46.51 %
Functions
25 %
Branches
100 %
//! Status-checked fetchers: a non-2xx response is an error carrying the
//! server's message, never a body to parse as success.
use wasm_bindgen::JsCast;
use wasm_bindgen::prelude::*;
use wasm_bindgen_futures::JsFuture;
use crate::escape::html_unescape;
/// The user-facing text of an error body: the JSON `message`, else the text
/// of an HTML fragment, else the bare status.
#[must_use]
pub fn error_message(status: u16, body: &str) -> String {
let text = serde_json::from_str::<serde_json::Value>(body)
.ok()
.and_then(|json| json.get("message")?.as_str().map(str::to_owned))
.unwrap_or_else(|| fragment_text(body));
match text.trim() {
"" => format!("HTTP {status}"),
text => text.to_owned(),
}
fn fragment_text(html: &str) -> String {
let mut text = String::with_capacity(html.len());
let mut in_tag = false;
for c in html.chars() {
match c {
'<' => in_tag = true,
'>' => in_tag = false,
_ if !in_tag => text.push(c),
_ => {}
html_unescape(&text)
/// GETs `url`; `accept` sets the `Accept` header when given.
pub async fn fetch_get(url: &str, accept: Option<&str>) -> Result<String, JsValue> {
let opts = web_sys::RequestInit::new();
opts.set_method("GET");
let headers = web_sys::Headers::new()?;
if let Some(accept) = accept {
headers.set("Accept", accept)?;
opts.set_headers(&headers);
let request = web_sys::Request::new_with_str_and_init(url, &opts)?;
let window = web_sys::window().ok_or("no window")?;
let response: web_sys::Response = JsFuture::from(window.fetch_with_request(&request))
.await?
.dyn_into()?;
let text = JsFuture::from(response.text()?)
.as_string()
.ok_or("not a string")?;
if response.ok() {
Ok(text)
} else {
Err(JsValue::from_str(&error_message(response.status(), &text)))
pub async fn fetch_json(url: &str) -> Result<String, JsValue> {
fetch_get(url, Some("application/json")).await
#[cfg(test)]
mod tests;