Function encode_doc_data_to_string

Source
pub fn encode_doc_data_to_string<T: Serialize>(
    data: &T,
) -> Result<String, String>
Expand description

Encodes a Rust struct into a JSON string, designed for use with Juno hooks.

This function facilitates the serialization of a Rust data structure representing a document data into a JSON string. It leverages Serde’s serialization capabilities, ensuring that any Rust type implementing the Serialize trait can be efficiently converted into a format compatible with Juno’s document requirements.

§Parameters

  • data: A reference to the Rust data structure to be serialized.

§Returns

  • Ok(String): A JSON string containing the serialized data.
  • Err(String): An error string if serialization fails.

§Examples

In a Juno hook, you might want to modify and then store updated document data:

#[derive(Serialize, Deserialize)]
struct Person {
    name: String,
    age: u32,
}

#[on_set_doc(collections = ["people"])]
async fn handle_set_person_doc(context: OnSetDocContext) -> Result<(), String> {
    let mut person: Person = decode_doc_data(&context.data.data.after.data)?;
    person.age += 1; // Increment the person's age

    let updated_data = encode_doc_data_to_string(&person)
        .expect("Failed to serialize updated document data");

    // Use `updated_data` to store the modified document

    Ok(())
}