I'd like to set default values for the query values in actix.
I know that there's a Default Trait for structs in the Rust standard library, but I honestly don't know how to apply it in this case.
The request query in my case might or might not provide the pagination values page and page_size.
Here's what I am trying to do:
src/adapters.rs (my handler module)
pub mod Basic {
#[derive(Deserialize, Default)]
pub struct ListQuery {
page: i64,
per_page: i64,
}
pub async fn articles_list(listQuery: Query<ListQuery>) -> impl Responder {
let query_options = ListQuery;
// should default to { page: 1, per_page: 10 }
// ...
}
}
So, how can I have e.g. per_page with a value of 10 if no query parameter is given?
The [derive(Default)] Macro derive the Default Implementation by calling ::default on all elements. For i64 this results in 0. What you actually want to do is implement Default yourself:
#[derive(Deserialize)]
pub struct ListQuery {
page: i64,
per_page: i64,
}
impl Default for ListQuery {
fn default() -> Self {
ListQuery {
page: 1,
per_page: 10
}
}
}
This should now provide you with the defaults you wanted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With