Trait TryIntoStruct

Source
pub trait TryIntoStruct {
    type Error;

    // Required method
    fn try_into_struct<S: DeserializeOwned>(self) -> Result<S, Self::Error>;
}
Expand description

Deserialize Trustfall query results or edge parameters into a Rust struct.

§Use with query results

Running a Trustfall query produces an iterator of BTreeMap<Arc<str>, FieldValue> outputs representing the query results. These maps all have a common “shape” — the same keys and the same value types — as determined by the query and schema.

This trait allows deserializing those query result maps into a dedicated struct, to get you easy access to strongly-typed data instead of FieldValue enums.

§Example

Say we ran a query like:

query {
    Order {
        item_name @output
        quantity @output
    }
}

Each of this query’s outputs contain a string named item_name and an integer named quantity. This trait allows us to define an output struct type:

#[derive(Debug, PartialEq, Eq, serde::Deserialize)]
struct Output {
    item_name: String,
    quantity: i64,
}

We can then unpack the query results into an iterator of such structs:


use trustfall_core::TryIntoStruct;

let results: Vec<_> = run_query()
    .expect("bad query arguments")
    .map(|v| v.try_into_struct().expect("struct definition did not match query result shape"))
    .collect();

assert_eq!(
    vec![
        Output {
            item_name: "widget".to_string(),
            quantity: 42,
        },
    ],
    results,
);

§Use with edge parameters

Edges defined in Trustfall schemas may take parameters, for example:

type NewsWebsite {
    latest_stories(count: Int!): [Story!]!
}

This trait can be used to deserialize &EdgeParameters into a struct specific to the parameters of that edge:

#[derive(Debug, PartialEq, Eq, serde::Deserialize)]
struct LatestStoriesParameters {
    count: usize
}

For example:


use trustfall_core::TryIntoStruct;

fn resolve_latest_stories(contexts: ContextIterator<Vertex>, parameters: &EdgeParameters) {
    let parameters: LatestStoriesParameters = parameters
        .try_into_struct()
        .expect("edge parameters did not match struct definition");
    let count = parameters.count;

    // then resolve the edge with the given count
}

Required Associated Types§

Required Methods§

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementations on Foreign Types§

Source§

impl TryIntoStruct for BTreeMap<Arc<str>, FieldValue>

Source§

type Error = Error

Source§

fn try_into_struct<S: DeserializeOwned>(self) -> Result<S, Error>

Implementors§