decode_doc_data

Function decode_doc_data 

Source
pub fn decode_doc_data<T: for<'a> Deserialize<'a>>(
    data: &[u8],
) -> Result<T, String>
Expand description

Decodes serialized document data into a Rust struct, tailored for use with Juno hooks.

This function is a utility for developers working with Juno hooks, particularly when receiving document data that needs to be processed. It uses Serde’s deserialization to convert a byte slice into a specified Rust data structure, allowing for direct manipulation of document data within hook functions.

§Parameters

  • data: A byte slice (&[u8]) containing the serialized document data.

§Returns

  • Ok(T): Successfully deserialized data of type T.
  • Err(String): An error string if deserialization fails.

§Examples

Within a Juno hook, you might receive document data that needs to be decoded:

#[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 person: Person = decode_doc_data(&context.data.data.after.data)
        .expect("Failed to decode document data");

    // Proceed with custom logic for the decoded `Person` instance
    println!("Received document for person: {}", person.name);

    Ok(())
}