How can I set default options for query parameters in actix handler?

1.4k views Asked by At

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?

1

There are 1 answers

2
standard_revolution On BEST ANSWER

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.