napi-rs / napi-rs

A framework for building compiled Node.js add-ons in Rust via Node-API
https://napi.rs
Other
5.96k stars 265 forks source link

Is there a way auto transform struct field which is i128 to BigInt? #2124

Open SoloJiang opened 4 months ago

richerfu commented 4 months ago

https://napi.rs/docs/concepts/values#bigint

#[napi]
pub struct A {
    pub test: BigInt,
}

#[napi]
impl A {
    #[napi]
    pub fn new() -> Self {
      Self {
            test: (100 as u128).into(),
        }
    }
}
SoloJiang commented 4 months ago

In my scenario, the same struct may need to be serialized and deserialized when receiving server data, and it may also be shared with Swift via uniffi-rs. Therefore, I would like the field type to be defined as i64 or i128, and to be automatically converted to BigInt only when interacting with JavaScript.

richerfu commented 4 months ago

How about to implement ToNapiValue FromNapiValue for your struct? But this solution can't generate ts type.

SoloJiang commented 4 months ago

Okay, but I prefer napi-rs can like serde that custom some field:

#[derive(Serialize, Deserialize, Debug)]
struct MyStruct {
    #[serde(serialize_with = "serialize_i64_as_string", deserialize_with = "deserialize_string_as_i64")]
    group_id: String,
}

For napi-rs:

#[napi]
struct MyStruct {
    #[napi(to_napi_with = "custom_to_napi",from_napi_with = "custom_from_napi")]
    group_id: i64,
}