From 8026ac574e6b8e1aeb868c970b780c72f655928b Mon Sep 17 00:00:00 2001 From: Akshay Date: Fri, 18 Dec 2020 17:33:17 +0530 Subject: improve product rating api --- src/handlers/product.rs | 44 ++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 42 insertions(+), 2 deletions(-) diff --git a/src/handlers/product.rs b/src/handlers/product.rs index 21bdbc9..41a47a0 100644 --- a/src/handlers/product.rs +++ b/src/handlers/product.rs @@ -1,11 +1,14 @@ -use crate::models::{NewProduct, Product, Rating, UpdateProduct}; +use crate::models::{Customer, NewProduct, Product, Rating, UpdateProduct}; +use crate::schema::customer::dsl as cust; use crate::schema::product::dsl::*; use crate::schema::rating::dsl as rating; use crate::TPool; use actix_web::{web, HttpResponse, Responder}; +use chrono::naive::NaiveDate; use diesel::prelude::*; use log::{error, info}; +use serde::{Deserialize, Serialize}; pub async fn new_product( pool: web::Data, @@ -83,6 +86,15 @@ pub async fn get_all_products(pool: web::Data) -> impl Responder { } } +#[derive(Serialize, Deserialize, Debug)] +struct ProductRating { + pub comment_text: Option, + pub comment_date: NaiveDate, + pub product_name: String, + pub customer_name: String, + pub stars: Option, +} + pub async fn get_product_reviews( pool: web::Data, product_id: web::Path, @@ -94,5 +106,33 @@ pub async fn get_product_reviews( .filter(rating::product_id.eq(pid)) .load::(&conn) .expect("Couldn't connect to DB"); - return HttpResponse::Ok().json(&rating_entries); + let json_ratings = rating_entries + .into_iter() + .map(move |p| { + let selected_product = product + .filter(id.eq(&p.product_id.unwrap())) + .limit(1) + .first::(&conn) + .unwrap() + .name + .clone(); + + let selected_customer = cust::customer + .filter(cust::id.eq(&p.customer_id.unwrap())) + .limit(1) + .first::(&conn) + .unwrap() + .username + .clone(); + + ProductRating { + comment_text: p.comment_text, + comment_date: p.comment_date.unwrap(), + product_name: selected_product, + customer_name: selected_customer, + stars: p.stars, + } + }) + .collect::>(); + return HttpResponse::Ok().json(&json_ratings); } -- cgit v1.2.3