Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Average rating of product variants #3

Merged
merged 2 commits into from
Feb 6, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion src/product_variant.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use crate::{
review_connection::ReviewConnection,
};

#[derive(Debug, Serialize, Deserialize, Hash, Eq, PartialEq, Copy, Clone, SimpleObject)]
#[derive(Debug, Serialize, Deserialize, PartialEq, Copy, Clone, SimpleObject)]
#[graphql(complex)]
pub struct ProductVariant {
/// UUID of the product variant.
Expand Down Expand Up @@ -58,6 +58,20 @@ impl ProductVariant {
Err(_) => return Err(Error::new("Retrieving reviews failed in MongoDB.")),
}
}

/// Retrieves average rating of product variant.
async fn average_rating<'a>(
&self,
ctx: &Context<'a>,
) -> Result<f32> {
let review_connection = self.reviews(&ctx, None, None, None).await?;
let reviews = review_connection.nodes;
let accumulated_reviews =
reviews.iter().fold(0, |prev_r, r| prev_r + r.rating as i32) as f32;
let total_count = review_connection.total_count as f32;
let average_rating = accumulated_reviews / total_count;
Ok(average_rating)
}
}

impl PartialOrd for ProductVariant {
Expand Down
Loading