lan-party-backend/web/src/util.rs

108 lines
2.5 KiB
Rust

use std::ops::Deref;
use anyhow::anyhow;
use reqwasm::http::{Method, Request};
use serde::{Deserialize, Serialize};
use thiserror::Error;
use wasm_bindgen::{prelude::*, JsCast};
use wasm_bindgen_futures::JsFuture;
use web_sys::{Headers, RequestInit, RequestMode, Response};
use yew::html::IntoPropValue;
pub async fn api_request<B: Serialize, R: for<'a> Deserialize<'a>>(
method: Method,
endpoint: &str,
body: Option<B>,
) -> Result<Option<R>, anyhow::Error> {
let api_key = "7de10bf6-278d-11ed-ad60-a8a15919d1b3";
let mut req = Request::new(&format!("http://localhost:8000/api/{}", endpoint))
.method(method)
.header("X-API-Key", api_key)
.mode(RequestMode::Cors);
if let Some(body) = body {
let value = JsValue::from_serde(&body)?;
req = req.body(
js_sys::JSON::stringify(&value)
.ok()
.map(JsValue::from)
.as_ref(),
);
}
let res = req.send().await?;
if let Ok(json) = res.json().await {
Ok(Some(json))
} else {
Ok(None)
}
}
#[macro_export]
macro_rules! clone {
($($var:ident),* $(,)? => $body:expr) => {{
$(let $var = $var.clone();)*
$body
}};
}
#[macro_export]
macro_rules! clone_cb {
($($var:ident),* $(,)? => $body:expr) => {
clone!($($var,)* => {
Callback::from($body)
})
};
($($var:ident),* $(,)? => $($param:ident),* $(,)? => $body:expr) => {
clone!($($var,)* => {
move |$($param,)*| {
Callback::from($body)
}
})
};
}
#[macro_export]
macro_rules! clone_cb_spawn {
($($var:ident),* => $body:expr) => {
clone_cb!($($var,)* => move |_| {
clone!($($var,)* => spawn_local(async move { $body }))
})
};
($($var:ident),* $(,)? => $($param:ident),* => $body:expr) => {
clone_cb!($($var,)* => $($param),* => move |_| {
clone!($($var,)* => spawn_local(async move { $body }))
})
};
}
#[macro_export]
macro_rules! init {
($var:ident => $body:expr) => {
clone!($var => use_mount(move || spawn_local(async move { $body })))
};
}
#[macro_export]
macro_rules! bind_value {
($value:ident) => {
(*$value).clone()
};
}
#[macro_export]
macro_rules! bind_change {
($value:ident) => {
clone_cb!($value => move |value| $value.set(value))
};
}
#[macro_export]
macro_rules! bind {
($value:ident) => {
Binding::<String>::from(Binding::new(bind_value!($value), bind_change!($value)))
};
}