use js_sys::Function;
use serde_json::Value;
use wasm_bindgen::prelude::*;
use crate::coinset::transport::FetchTransport;
use crate::coinset::CoinsetClient as CoreClient;
#[wasm_bindgen]
pub struct CoinsetClient {
inner: CoreClient<FetchTransport>,
}
#[wasm_bindgen]
impl CoinsetClient {
#[wasm_bindgen(constructor)]
pub fn new(base_url: &str, fetch: Function) -> CoinsetClient {
CoinsetClient {
inner: CoreClient::with_transport(base_url, FetchTransport::new(fetch)),
}
}
#[wasm_bindgen]
pub async fn request(&self, endpoint: String, body: JsValue) -> Result<JsValue, JsValue> {
let body = to_json(body)?;
let json = self
.inner
.post(&endpoint, &body)
.await
.map_err(to_js_error)?;
to_js(&json)
}
#[wasm_bindgen(js_name = requestRaw)]
pub async fn request_raw(&self, endpoint: String, body: JsValue) -> Result<JsValue, JsValue> {
let body = to_json(body)?;
let json = self
.inner
.post_raw(&endpoint, &body)
.await
.map_err(to_js_error)?;
to_js(&json)
}
}
fn to_json(value: JsValue) -> Result<Value, JsValue> {
if value.is_undefined() || value.is_null() {
return Ok(Value::Object(Default::default()));
}
serde_wasm_bindgen::from_value(value).map_err(|e| JsValue::from_str(&e.to_string()))
}
fn to_js(value: &Value) -> Result<JsValue, JsValue> {
serde_wasm_bindgen::to_value(value).map_err(|e| JsValue::from_str(&e.to_string()))
}
fn to_js_error(err: crate::types::ChiaQueryError) -> JsValue {
js_sys::Error::new(&err.to_string()).into()
}