Dependent Fields
A dependent field is an output-only field whose value is recomputed whenever at least one of its
declared parent fields changes (e.g. username_last_updated_at should only update whenever
username changes) -- see when the resolver runs.
- Declared with
#[depends_on("parent", ...)]-- at least one parent, each a string literal naming another field on the schema (lax, required, virtual, or another dependent field; no circular dependencies). - Requires a resolver via
#[resolve(|ctx, opts| -> T)], run whenever a parent changes. - Requires a default via
#[default(value_or_resolver)], used until a parent first changes (and as the fallback if none of the parents were ever provided). - May use
#[readonly]to stop accepting further changes once its value differs from its default. - May have
on_deleteandon_successevent handlers. - Requires
output(...)on the schema, since it never appears on the input struct.
Example
computed depends on value (a lax field defaulting to 0) and resolves to value + 1:
use ivo::ivo_schema;
#[ivo_schema(
input(DataInput, ivo_attrs(derive(Debug, Clone, PartialEq))),
output(Data, ivo_attrs(derive(Debug, Clone, PartialEq)))
)]
mod dependents_schema {
struct Fields {
#[lax(0)]
pub value: i32,
#[depends_on("value")]
#[default(1)]
#[resolve(|ctx, _opts| ctx.values().value.unwrap() + 1)]
pub computed: i32,
}
}
fn main() {
// `value` isn't provided: it gets its default (0), which doesn't trigger `computed`'s
// resolver, so `computed` keeps its own default (1).
let created = dependents_schema::DataModel
.create(dependents_schema::PartialDataInput { value: None })
.unwrap();
println!("{:?}", created); // Data { value: 0, computed: 1 }
let created = dependents_schema::DataModel
.create(dependents_schema::PartialDataInput { value: Some(5) })
.unwrap();
println!("{:?}", created); // Data { value: 5, computed: 6 }
let updated = dependents_schema::DataModel
.update(
created,
dependents_schema::PartialDataInput { value: Some(10) },
)
.unwrap();
println!("{:?}", updated); // PartialData { value: Some(10), computed: Some(11) }
}
ctx.values() inside the resolver gives access to every field resolved so far in the same
create/update call, including sibling dependents earlier in the dependency graph -- see
Execution Pipeline for the exact phase ordering.
When the resolver runs
- On create, a dependent resolves when at least one of its parents:
- is a required or virtual field that was provided and accepted;
- is a lax field that was provided and accepted with a value other than its static default, or whose default comes from a resolver (a closure or a path to a zero-argument function), provided or not;
- is a dependent field that resolved to a value other than its default, or whose default comes from a resolver.
- On update, a dependent resolves when at least one of its parents:
- is a virtual field that was provided and accepted (always, since it has no previous value);
- is a required or lax field that was provided and accepted with a value other than its previous one;
- is a dependent field that resolved to a value other than its previous one.
A dependent that resolves to the value it already had is not a change, so the dependents below it don't resolve. Dependents resolve in dependency order, each one at most once per operation, after all its parents: a dependent with several parents never resolves twice.
A parent left at its static default
use ivo::ivo_schema;
#[ivo_schema(
input(PostInput, ivo_attrs(derive(Debug, Clone, PartialEq))),
output(Post, ivo_attrs(derive(Debug, Clone, PartialEq)))
)]
mod post_schema {
struct Fields {
#[lax(String::new())]
pub title: String,
#[depends_on("title")]
#[default("untitled".to_string())]
#[resolve(|ctx, _| {
println!("(the slug resolver ran)");
ctx.values().title.clone().unwrap().to_lowercase().replace(' ', "-")
})]
pub slug: String,
}
}
fn main() {
use post_schema::{PartialPostInput, PostModel};
// the title left at, or provided with, its static default: no change, no resolver
let post = PostModel.create(PartialPostInput { title: None }).unwrap();
println!("{:?}", post); // Post { title: "", slug: "untitled" }
let post = PostModel.create(PartialPostInput { title: Some(String::new()) }).unwrap();
println!("{:?}", post); // Post { title: "", slug: "untitled" }
// another title: the slug resolves
let post = PostModel
.create(PartialPostInput { title: Some("Hello World".into()) })
.unwrap(); // (the slug resolver ran)
println!("{:?}", post); // Post { title: "Hello World", slug: "hello-world" }
}
A dependent resolving to its previous value
use ivo::ivo_schema;
#[ivo_schema(
input(ProductInput, ivo_attrs(derive(Debug, Clone, PartialEq))),
output(Product, ivo_attrs(derive(Debug, Clone, PartialEq)))
)]
mod product_schema {
struct Fields {
#[lax(0)]
pub price: u32,
#[depends_on("price")]
#[default("free".to_string())]
#[resolve(|ctx, _| {
if ctx.values().price.unwrap() < 100 { "cheap" } else { "premium" }.to_string()
})]
pub band: String,
#[depends_on("band")]
#[default(String::new())]
#[resolve(|ctx, _| {
println!("(the badge resolver ran)");
if ctx.values().band.as_deref() == Some("premium") { "star" } else { "" }.to_string()
})]
pub badge: String,
}
}
fn main() {
use product_schema::{PartialProductInput, ProductModel};
let product = ProductModel
.create(PartialProductInput { price: Some(10) })
.unwrap(); // (the badge resolver ran)
println!("{:?}", product); // Product { price: 10, band: "cheap", badge: "" }
// the band resolves to its previous value ("cheap"): the badge doesn't resolve
let cheaper = ProductModel
.update(product.clone(), PartialProductInput { price: Some(20) })
.unwrap();
println!("{:?}", cheaper); // PartialProduct { price: Some(20), band: None, badge: None }
// the band changes: the badge resolves too
let premium = ProductModel
.update(product, PartialProductInput { price: Some(150) })
.unwrap(); // (the badge resolver ran)
println!("{:?}", premium); // PartialProduct { price: Some(150), band: Some("premium"), badge: Some("star") }
}
Several parents changing at once
use ivo::ivo_schema;
#[ivo_schema(
input(UserInput, ivo_attrs(derive(Debug, Clone, PartialEq))),
output(User, ivo_attrs(derive(Debug, Clone, PartialEq)))
)]
mod user_schema {
struct Fields {
#[lax(String::new())]
pub first_name: String,
#[lax(String::new())]
pub last_name: String,
#[depends_on("first_name", "last_name")]
#[default(String::new())]
#[resolve(|ctx, _| {
println!("(the initials resolver ran)");
let initial = |name: &Option| name.as_deref().and_then(|n| n.chars().next());
initial(&ctx.values().first_name).into_iter().chain(initial(&ctx.values().last_name)).collect()
})]
pub initials: String,
}
}
fn main() {
use user_schema::{PartialUserInput, UserModel};
let names = |first: &str, last: &str| PartialUserInput {
first_name: Some(first.into()),
last_name: Some(last.into()),
};
let ada = UserModel.create(names("Ada", "Lovelace")).unwrap(); // (the initials resolver ran)
println!("{:?}", ada); // User { first_name: "Ada", last_name: "Lovelace", initials: "AL" }
// both parents change: the resolver still runs once
let updated = UserModel.update(ada, names("Grace", "Hopper")).unwrap(); // (the initials resolver ran)
println!("{:?}", updated); // PartialUser { first_name: Some("Grace"), last_name: Some("Hopper"), initials: Some("GH") }
}
Readonly
#[readonly] (with a static default) locks the field once its value differs from its default:
its parents changing no longer re-resolve it.
use ivo::ivo_schema;
#[ivo_schema(
input(UserInput, ivo_attrs(derive(Debug, Clone, PartialEq))),
output(User, ivo_attrs(derive(Debug, Clone, PartialEq)))
)]
mod user_schema {
struct Fields {
#[lax("Ada".to_string())]
pub first_name: String,
#[lax("Lovelace".to_string())]
pub last_name: String,
#[depends_on("first_name", "last_name")]
#[default(String::new())]
#[readonly]
#[resolve(|ctx, _| {
let values = ctx.values();
format!("{} {}", values.first_name.clone().unwrap(), values.last_name.clone().unwrap())
})]
pub full_name: String,
}
}
fn main() {
use user_schema::{PartialUserInput, UserModel};
let first_name = |name: &str| PartialUserInput { first_name: Some(name.into()), last_name: None };
// the names are left at their defaults: full_name keeps its own ("")
let created = UserModel
.create(PartialUserInput { first_name: None, last_name: None })
.unwrap();
println!("{:?}", created); // User { first_name: "Ada", last_name: "Lovelace", full_name: "" }
// a name changes while full_name is at its default: it resolves
let updated = UserModel.update(created.clone(), first_name("Grace")).unwrap();
println!("{:?}", updated); // PartialUser { first_name: Some("Grace"), last_name: None, full_name: Some("Grace Lovelace") }
// full_name now differs from its default: it's locked
let current = created.clone_with_updates(&updated);
let updated_again = UserModel.update(current, first_name("James")).unwrap();
println!("{:?}", updated_again); // PartialUser { first_name: Some("James"), last_name: None, full_name: None }
}
More examples
Try it in the browser
value is a lax field with a default of 0. computed is a dependent field that equals
value + 1 (with its own fallback default of 1).