From 5037dc99ec190017c82ed6768b9f18b57696dbb9 Mon Sep 17 00:00:00 2001 From: Eric Date: Thu, 30 Jun 2022 20:50:20 +0200 Subject: [PATCH] Create a `num_items_and_pages` on the `paginator` (#768) * Create a `num_items_and_pages` on the `paginator` This method allows us to get both number of items and pages of a paginator with only one database query. * Improve documentation * Create a dedicated struct for items and pages number --- src/executor/paginator.rs | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/src/executor/paginator.rs b/src/executor/paginator.rs index 4627ce2a..520e7025 100644 --- a/src/executor/paginator.rs +++ b/src/executor/paginator.rs @@ -24,6 +24,15 @@ where pub(crate) selector: PhantomData, } +/// Define a structure containing the numbers of items and pages of a Paginator +#[derive(Clone, Debug)] +pub struct ItemsAndPagesNumber { + /// The total number of items of a paginator + pub number_of_items: usize, + /// The total number of pages of a paginator + pub number_of_pages: usize, +} + // LINT: warn if paginator is used without an order by clause impl<'db, C, S> Paginator<'db, C, S> @@ -80,10 +89,23 @@ where /// Get the total number of pages pub async fn num_pages(&self) -> Result { let num_items = self.num_items().await?; - let num_pages = (num_items / self.page_size) + (num_items % self.page_size > 0) as usize; + let num_pages = self.compute_pages_number(num_items); Ok(num_pages) } + /// Get the total number of items and pages + pub async fn num_items_and_pages(&self) -> Result { + let number_of_items = self.num_items().await?; + let number_of_pages = self.compute_pages_number(number_of_items); + + Ok(ItemsAndPagesNumber { number_of_items, number_of_pages }) + } + + /// Compute the number of pages for the current page + fn compute_pages_number(&self, num_items: usize) -> usize { + (num_items / self.page_size) + (num_items % self.page_size > 0) as usize + } + /// Increment the page counter pub fn next(&mut self) { self.page += 1;