-
Notifications
You must be signed in to change notification settings - Fork 2
Understanding the Defaults
Andrey edited this page Oct 17, 2023
·
1 revision
There is a concept:
- if the input model field is, for example, String (and not Option) - the field is required.
- if the input model field is Option - the field is optional;
- if there is an Default Value in the field description - the field became optional in any cases;
#[derive(MyHttpInput)]
pub struct DefaultStringQueryInputModel {
#[http_query(name : "noDefault", description=: "Test")]
pub no_default: String, //Required Field
#[http_query(name = "withDefault"; description: "MyDescription", default: "MyDefault")]
pub with_default: String, //Optional Field
#[http_query(name : "noDefaultOpt", description=: "Test")]
pub no_default_opt: Option<String>, //Optional Field
#[http_query(name = "withDefaultOpt"; description: "MyDescription", default: "MyDefault")]
pub with_default_opt: Option<String>, //Optional Field
}A default value can be specified inside the field description as a Value for types such as:
- i8...i64;
- u8...u64;
- f32, f64
- String,
- DateTimeAsMicroseconds
Example
#[derive(MyHttpInput)]
pub struct DefaultStringQueryInputModel {
#[http_query(name = "withDefault"; description: "MyDescription", default: "MyDefault")]
pub with_default: String,
}Any Enum Case can be marked as Default.
#[derive(MyHttpStringEnum)]
pub enum MyEnumModel {
#[http_enum_case(id: 0, value:"myCase1", description = "My Case 1 Description", default)]
Case1,
#[http_enum_case(id: 1, description = "My Case 1 Description")]
Case2,
#[http_enum_case(id: 2, description = "My Case 1 Description")]
Case3,
}
#[derive(MyHttpInput)]
pub struct MyHttpInput {
#[http_query(name = "myEnum", description = "a", default)] // <-- Default parameter without value takes the Default case of MyEnumModel
pub my_enum: MyEnumModel,
}Under the hood, it generates the Default Trait and Some Auxiliary methods, which are used to create the Default Version of Enum if needed.
impl MyEnumModel {
pub fn create_default() -> Result<Self, my_http_server::HttpFailResult> {
Ok(Self::default())
}
pub fn default_as_str() -> &'static str {
"Case1"
}
}
impl std::default::Default for MyEnumModel {
fn default() -> Self {
Self::Case1
}
}