Skip to main content

FromJs

Derive Macro FromJs 

Source
#[derive(FromJs)]
{
    // Attributes available to this derive:
    #[qjs]
}
Expand description

A macro for deriving FromJs for plain-data structs.

Generated impls treat the Rust value as a plain JavaScript object (for named-field structs), a JavaScript array (for tuple structs), or undefined (for unit structs) and read each field in turn via Object::get or Array::get.

§Attribute options

Options can be supplied via a #[qjs(...)] attribute on the container or individual fields.

OptionScopeValueDescription
crateContainerStringPath of the rquickjs crate, in case the macro cannot resolve it automatically.
rename_allContainerCasingRewrites every field name using the given case (lowercase, UPPERCASE, camelCase, PascalCase, snake_case, or SCREAMING_SNAKE) before reading it from the JS object.
renameFieldStringUse the supplied string as the JavaScript property name instead of the Rust identifier.

§Example

use rquickjs::{Context, FromJs, Runtime};

#[derive(Debug, PartialEq, FromJs)]
#[qjs(rename_all = "camelCase")]
struct Spec {
    some_value: u32,
    #[qjs(rename = "labelText")]
    label_text: String,
}

let rt = Runtime::new().unwrap();
let ctx = Context::full(&rt).unwrap();
ctx.with(|ctx| {
    let spec: Spec = ctx
        .eval(r#"({ someValue: 2, labelText: "beta" })"#)
        .unwrap();
    assert_eq!(spec, Spec { some_value: 2, label_text: "beta".into() });
});

§Incompatibility with class

This derive cannot be stacked on a type that is also tagged with #[rquickjs::class]. #[class] already generates a FromJs impl that round-trips through a Class<Self> instance, whereas this derive reads field-by-field from a plain JS object. The two representations are mutually exclusive; combining them produces a compile error pointing at the offending derive.