encode_doc_data

Function encode_doc_data 

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

Encodes a Rust struct into serialized document data, designed for use with Juno hooks.

When preparing document data to be stored, this function facilitates the serialization of a Rust data structure into a byte vector. 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(Vec<u8>): A byte vector 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(&person)
        .expect("Failed to serialize updated document data");

    // Use `updated_data` to store the modified document

    Ok(())
}