Skip to main content

ankurah_core/model/
tsify.rs

1#![allow(clippy::wrong_self_convention)]
2
3#[cfg(feature = "wasm")]
4pub use serde_wasm_bindgen;
5#[cfg(feature = "wasm")]
6use wasm_bindgen::{JsCast, JsValue};
7
8pub struct SerializationConfig {
9    pub missing_as_null: bool,
10    pub hashmap_as_object: bool,
11    pub large_number_types_as_bigints: bool,
12}
13
14/// `Tsify` is a trait that allows you to convert a type to and from JavaScript.
15/// Can be implemented manually if you need to customize the serialization or deserialization.
16pub trait Tsify {
17    #[cfg(feature = "wasm")]
18    type JsType: JsCast;
19
20    const DECL: &'static str;
21    const SERIALIZATION_CONFIG: SerializationConfig =
22        SerializationConfig { missing_as_null: false, hashmap_as_object: false, large_number_types_as_bigints: false };
23
24    #[cfg(feature = "wasm")]
25    #[inline]
26    fn into_js(&self) -> Result<Self::JsType, serde_wasm_bindgen::Error>
27    where Self: serde::Serialize {
28        let config = <Self as Tsify>::SERIALIZATION_CONFIG;
29        let serializer = serde_wasm_bindgen::Serializer::new()
30            .serialize_missing_as_null(config.missing_as_null)
31            .serialize_maps_as_objects(config.hashmap_as_object)
32            .serialize_large_number_types_as_bigints(config.large_number_types_as_bigints);
33        self.serialize(&serializer).map(JsCast::unchecked_from_js)
34    }
35
36    #[cfg(feature = "wasm")]
37    #[inline]
38    fn from_js<T: Into<JsValue>>(js: T) -> Result<Self, serde_wasm_bindgen::Error>
39    where Self: serde::de::DeserializeOwned {
40        serde_wasm_bindgen::from_value(js.into())
41    }
42}