Search code examples
rustwebassemblywasm-bindgen

Importing a js function with an object parameter - Rust / wasm_bindgen


I'm trying to use a JS function from within rust with wasm_bindgen, the function has an object parameter similar to functions like fetch:

#[wasm_bindgen]
extern "C" {
    #[wasm_bindgen]
    fn fetch(resource: &str, config: &JsValue);
}

(just using fetch as an example, I know that there are better ways to use fetch from rust...)

I'm not sure how to model the config object in rust.

I tried using JsValue but it seems that JsValue can only be created from primitive types and not from objects.

I've seen online some suggestions that serde can help here but I couldn't find any concrete examples, and my attempt to get it to work myself were not fruitful either.

Thanks in advance for looking into this!


Solution

  • It looks like you can either use js_sys::Reflect to access or set arbitrary values, or you can use serde to parse/unparse values

    For the first method, this resource explains how to read or write a property on an untyped object: https://rustwasm.github.io/docs/wasm-bindgen/reference/accessing-properties-of-untyped-js-values.html and an example of using this interface can be found in web-sys itself, which defines the RequestInit object which is used when building the config object for fetch(): https://docs.rs/web-sys/0.3.50/src/web_sys/features/gen_RequestInit.rs.html#4

    The other way is to use serde. An example of this can be found at https://rustwasm.github.io/docs/wasm-bindgen/examples/fetch.html and a more detailed explanation can be found at https://rustwasm.github.io/docs/wasm-bindgen/reference/arbitrary-data-with-serde.html

    After defining the objects to serialize and deserialize, the JsValue::from_serde() and .into_serde() can be used to convert to and from a JsValue