#serialization #javascript #serde-json #templating #template #automatic #literals

serialize-to-javascript

Serialize a serde::Serialize item to a JavaScript literal template using serde_json

2 releases

0.1.1 Feb 8, 2022
0.1.0 Feb 8, 2022

#716 in Encoding

Download history 21860/week @ 2023-12-02 22720/week @ 2023-12-09 18844/week @ 2023-12-16 13876/week @ 2023-12-23 15842/week @ 2023-12-30 18745/week @ 2024-01-06 20823/week @ 2024-01-13 19885/week @ 2024-01-20 19123/week @ 2024-01-27 18916/week @ 2024-02-03 20548/week @ 2024-02-10 26592/week @ 2024-02-17 31068/week @ 2024-02-24 29793/week @ 2024-03-02 28204/week @ 2024-03-09 23542/week @ 2024-03-16

116,837 downloads per month
Used in 103 crates (6 directly)

MIT/Apache

16KB
107 lines

Serialize to JavaScript

This library provides serialization from serde::Serialize into JavaScript utilizing serde_json. It also provides a very simple templating mechanism along with derive macros to automatically derive them for suitable types.

[dependencies]
serialize-to-javascript = "0.1"

Examples

Serialization

use serialize_to_javascript::{Options, Serialized};

fn main() -> serialize_to_javascript::Result<()> {
    let raw_value = serde_json::value::to_raw_value("foo'bar")?;
    let serialized = Serialized::new(&raw_value, &Options::default());
    assert_eq!(serialized.into_string(), "JSON.parse('\"foo\\'bar\"')");
    Ok(())
}

Templating

main.rs:

use serialize_to_javascript::{default_template, DefaultTemplate, Options, Serialized, Template};

#[derive(Template)]
#[default_template("keygen.js")]
struct Keygen<'a> {
    key: &'a str,
    length: usize,

    #[raw]
    optional_script: &'static str,
}

fn main() -> serialize_to_javascript::Result<()> {
    let keygen = Keygen {
        key: "asdf",
        length: 4,
        optional_script: "console.log('hello, from my optional script')",
    };

    let _output: Serialized = keygen.render_default(&Options::default())?;

    Ok(())
}

keygen.js:

const keygenKey = __TEMPLATE_key__
const keygenLength = __TEMPLATE_length__

__RAW_optional_script__

// app logic, we are ensuring the length is equal to the expected one for some reason
if (keygenKey.length === keygenLength) {
    console.log("okay!")
} else {
    console.error("oh no!")
}

License

Licensed under either of Apache License 2.0, Version or MIT license at your option.

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Dependencies

~0.7–1.4MB
~33K SLoC