Options du schéma
Les options globales du schéma se configurent dans la seconde closure de
IvoModel::new(..., |o| o...). Utilisez-les lorsqu'une règle ou un effet de bord implique plusieurs
champs, ou lorsque vous voulez réagir à l'entité dans son ensemble.
on_success
Enregistre un gestionnaire qui s'exécute après un create ou update réussi. Un tableau de champs
vide signifie "se déclencher à chaque succès" ; sinon, il se déclenche lorsqu'au moins un des
champs listés fait partie du payload de succès.
use std::{future::ready, sync::LazyLock};
use ivo::{lax_field, IvoInputStruct, IvoModel, IvoStruct};
#[derive(Clone, Debug, PartialEq, IvoInputStruct)]
struct DataInput {
pub a: i32,
pub b: i32,
}
#[derive(Clone, Debug, PartialEq, IvoStruct)]
struct Data {
pub a: i32,
pub b: i32,
}
static MODEL: LazyLock<IvoModel<DataInput, Data>> = LazyLock::new(|| {
IvoModel::new(
|f| {
f.field(lax_field("a").default(0))
.field(lax_field("b").default(0))
},
|o| {
o.on_success([], |b| {
b.handle(|_, _| {
println!("entity created or updated");
ready(())
})
})
.on_success(["a", "b"], |b| {
b.handle(|_, _| {
println!("a and/or b changed");
ready(())
})
})
},
)
});
Voir l'exemple exécutable
option_on_success.rs
pour plus de détails, y compris les champs dépendants et virtuels.
on_delete
Enregistre un ou plusieurs gestionnaires qui s'exécutent lorsque model.delete(&entity, None).await
est invoqué. Ils sont déclenchés pour l'entité entière, en plus de tout gestionnaire on_delete par
champ.
use std::{future::ready, sync::LazyLock};
use ivo::{lax_field, IvoInputStruct, IvoModel, IvoStruct};
#[derive(Clone, Debug, PartialEq, IvoInputStruct)]
struct DataInput {
pub a: i32,
}
#[derive(Clone, Debug, PartialEq, IvoStruct)]
struct Data {
pub a: i32,
}
static MODEL: LazyLock<IvoModel<DataInput, Data>> = LazyLock::new(|| {
IvoModel::new(
|f| f.field(lax_field("a").default(0)),
|o| {
o.on_delete(|data, _| {
println!("deleting entity with a = {}", data.a);
ready(())
})
},
)
});
Voir les tests should_properly_trigger_on_delete_handlers dans
rs/tests/options/mod.rs.
ignore
Une règle d'ignorance groupée permet d'ignorer le traitement de plusieurs champs lax ou virtuels à
la fois, selon une condition partagée. Le résolveur reçoit le contexte d'entrée et retourne true
pour ignorer le groupe. Nécessite au moins deux champs.
use std::{future::ready, sync::LazyLock};
use ivo::{lax_field, IvoContext, IvoInputStruct, IvoModel, IvoStruct};
#[derive(Clone, Debug, PartialEq, IvoInputStruct)]
struct DataInput {
pub email: String,
pub phone: String,
}
#[derive(Clone, Debug, PartialEq, IvoStruct)]
struct Data {
pub email: String,
pub phone: String,
}
static MODEL: LazyLock<IvoModel<DataInput, Data>> = LazyLock::new(|| {
IvoModel::new(
|f| {
f.field(lax_field("email").default(String::new()))
.field(lax_field("phone").default(String::new()))
},
|o| {
o.ignore(["email", "phone"], |ctx: IvoContext<DataInput, Data>, _| {
// ignore both when a special flag is present
ready(ctx.input().email == "skip")
})
},
)
});
Voir lax_with_ignore.rs
et les tests d'ignorance groupée dans
rs/tests/options/ignore.rs.
ignore_update
Même idée que ignore, mais évalué uniquement lors des mises à jour. Un tableau de champs vide
applique la règle à l'entité entière. Avec deux champs ou plus, elle s'applique au groupe.
use std::{future::ready, sync::LazyLock};
use ivo::{lax_field, IvoInputStruct, IvoModel, IvoStruct};
#[derive(Clone, Debug, PartialEq, IvoInputStruct)]
struct DataInput {
pub a: i32,
pub b: i32,
}
#[derive(Clone, Debug, PartialEq, IvoStruct)]
struct Data {
pub a: i32,
pub b: i32,
}
static MODEL: LazyLock<IvoModel<DataInput, Data>> = LazyLock::new(|| {
IvoModel::new(
|f| {
f.field(lax_field("a").default(0))
.field(lax_field("b").default(0))
},
|o| {
o.ignore_update(["a", "b"], |input: PartialDataInput, _, _| {
ready(input.a == Some(42))
})
},
)
});
Voir lax_with_ignore_update.rs
et les tests groupés dans
rs/tests/options/ignore_update.rs.
required
Une règle de requis groupée impose qu'au moins un des champs lax ou virtuels listés soit fourni. Le
résolveur retourne Some(errors) lorsque l'exigence n'est pas satisfaite. Elle est couramment
utilisée pour des règles du type "fournir un email ou un téléphone".
use std::{future::ready, sync::LazyLock};
use ivo::{lax_field, IvoContext, IvoInputStruct, IvoModel, IvoStruct};
#[derive(Clone, Debug, PartialEq, IvoInputStruct)]
struct UserInput {
pub email: Option<String>,
pub phone_number: Option<String>,
}
#[derive(Clone, Debug, PartialEq, IvoStruct)]
struct User {
pub email: Option<String>,
pub phone_number: Option<String>,
}
static USER_MODEL: LazyLock<IvoModel<UserInput, User>> = LazyLock::new(|| {
IvoModel::new(
|f| {
f.field(lax_field("email").default(None::<String>))
.field(lax_field("phone_number").default(None::<String>))
},
|o| {
o.required(["email", "phone_number"], |ctx: IvoContext<UserInput, User>, _| {
if ctx.is_update() || ctx.input().email.is_some() || ctx.input().phone_number.is_some() {
return ready(None);
}
let reason = "provide either an email or a phone number";
ready(Some(
UserInputErrors::new()
.with_email(reason, None)
.with_phone_number(reason, None),
))
})
},
)
});
UserInputErrors est généré en dérivant IvoInputStruct. Voir le même schéma dans
main_demo/src/domain.rs
et les tests groupés dans
rs/tests/options/required.rs.
post_validate
La validation transversale aux champs s'exécute après les validateurs de chaque champ individuel. Utilisez-la pour valider des combinaisons de champs lax, requis ou virtuels. Nécessite au moins deux champs.
use std::{future::ready, sync::LazyLock};
use ivo::{lax_field, IvoContext, IvoInputStruct, IvoModel, IvoStruct};
#[derive(Clone, Debug, PartialEq, IvoInputStruct)]
struct UserInput {
pub password: String,
pub confirm_password: String,
}
#[derive(Clone, Debug, PartialEq, IvoStruct)]
struct User {
pub password: String,
pub confirm_password: String,
}
static USER_MODEL: LazyLock<IvoModel<UserInput, User>> = LazyLock::new(|| {
IvoModel::new(
|f| {
f.field(lax_field("password").default(String::new()))
.field(lax_field("confirm_password").default(String::new()))
},
|o| {
o.post_validate(["password", "confirm_password"], |b| {
b.validate(|ctx: IvoContext<UserInput, User>, _| {
let input = ctx.input();
if input.password != input.confirm_password {
let mut errors = UserInputErrors::new();
errors.set_confirm_password("passwords do not match", None);
return ready(Err(errors));
}
ready(Ok(None))
})
})
},
)
});
Voir la validation transversale dans
main_demo/src/domain.rs
et les tests groupés dans
rs/tests/options/post_validate.rs.
Options de contexte personnalisées
IvoModel accepte un paramètre de type CtxOptions pour faire transiter des données personnalisées
à travers les opérations de création, de mise à jour et de suppression (injection de dépendances,
contexte de requête, cache, etc.).
use ivo::{IvoContext, IvoModel, IvoRwCtxOptions};
#[derive(Clone, Default)]
struct MyCtxOptions {
db: Database,
}
type Ctx = IvoContext<Input, Output>;
type RwCtxOptions = IvoRwCtxOptions<MyCtxOptions>;
static MODEL: LazyLock<IvoModel<Input, Output, MyCtxOptions>> = LazyLock::new(|| {
IvoModel::new(
|f| { /* field definitions */ },
|o| {
o.post_validate(["a", "b"], |b| {
b.validate(|ctx: Ctx, options: RwCtxOptions| async move {
let db = &options.read().await.db;
// use db ...
Ok(None)
})
})
},
)
});
Voir main_demo/src/domain.rs
pour un exemple complet et fonctionnel.
Payloads d'erreur personnalisés avec IvoErrorSanitizer
Par défaut, ivo retourne les erreurs sous forme de HashMap<String, FieldError<()>>. Vous pouvez
changer la forme du payload d'erreur en implémentant IvoErrorSanitizer :
use std::{collections::HashMap, future::ready};
use ivo::{IvoErrorPayload, IvoErrorSanitizer};
#[derive(Clone)]
struct MyCtxOptions;
struct MyErrorSanitizer;
impl IvoErrorSanitizer<MyCtxOptions> for MyErrorSanitizer {
type Metadata = Vec<String>;
type Payload = HashMap<String, Vec<String>>;
fn sanitize(payload: IvoErrorPayload<Self::Metadata>, _o: &MyCtxOptions) -> Self::Payload {
payload
.into_iter()
.map(|(name, err)| {
let mut errors = vec![err.reason];
if let Some(meta) = err.metadata {
errors.extend(meta);
}
(name, errors)
})
.collect()
}
}
Le sanitizer devient le cinquième paramètre de type de IvoModel :
IvoModel<Input, Output, MyCtxOptions, Timestamp, MyErrorSanitizer>
Voir l'exemple complet dans
rs/tests/extras/error_sanitizer.rs,
ainsi que la documentation du trait sur docs.rs/crate/ivo.
Référence de l'API
Pour la liste exhaustive des builders d'options et de leurs signatures, voir :
- docs.rs/crate/ivo — rustdoc hébergé pour le crate publié.
- rustdoc local — exécutez
cargo doc --no-deps --opendepuis le répertoirers/pour parcourir la même référence générée localement.