aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAkshay <[email protected]>2020-12-18 12:03:17 +0000
committerAkshay <[email protected]>2020-12-18 12:03:17 +0000
commit8026ac574e6b8e1aeb868c970b780c72f655928b (patch)
tree2affcc7862bbd268b4adfb03b745f3db2957a80b
parent41dcd48b71e7f5a8df79d6b0871a2bf95b7aa80e (diff)
improve product rating api
-rw-r--r--src/handlers/product.rs44
1 files 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 @@
1use crate::models::{NewProduct, Product, Rating, UpdateProduct}; 1use crate::models::{Customer, NewProduct, Product, Rating, UpdateProduct};
2use crate::schema::customer::dsl as cust;
2use crate::schema::product::dsl::*; 3use crate::schema::product::dsl::*;
3use crate::schema::rating::dsl as rating; 4use crate::schema::rating::dsl as rating;
4use crate::TPool; 5use crate::TPool;
5 6
6use actix_web::{web, HttpResponse, Responder}; 7use actix_web::{web, HttpResponse, Responder};
8use chrono::naive::NaiveDate;
7use diesel::prelude::*; 9use diesel::prelude::*;
8use log::{error, info}; 10use log::{error, info};
11use serde::{Deserialize, Serialize};
9 12
10pub async fn new_product( 13pub async fn new_product(
11 pool: web::Data<TPool>, 14 pool: web::Data<TPool>,
@@ -83,6 +86,15 @@ pub async fn get_all_products(pool: web::Data<TPool>) -> impl Responder {
83 } 86 }
84} 87}
85 88
89#[derive(Serialize, Deserialize, Debug)]
90struct ProductRating {
91 pub comment_text: Option<String>,
92 pub comment_date: NaiveDate,
93 pub product_name: String,
94 pub customer_name: String,
95 pub stars: Option<i32>,
96}
97
86pub async fn get_product_reviews( 98pub async fn get_product_reviews(
87 pool: web::Data<TPool>, 99 pool: web::Data<TPool>,
88 product_id: web::Path<i32>, 100 product_id: web::Path<i32>,
@@ -94,5 +106,33 @@ pub async fn get_product_reviews(
94 .filter(rating::product_id.eq(pid)) 106 .filter(rating::product_id.eq(pid))
95 .load::<Rating>(&conn) 107 .load::<Rating>(&conn)
96 .expect("Couldn't connect to DB"); 108 .expect("Couldn't connect to DB");
97 return HttpResponse::Ok().json(&rating_entries); 109 let json_ratings = rating_entries
110 .into_iter()
111 .map(move |p| {
112 let selected_product = product
113 .filter(id.eq(&p.product_id.unwrap()))
114 .limit(1)
115 .first::<Product>(&conn)
116 .unwrap()
117 .name
118 .clone();
119
120 let selected_customer = cust::customer
121 .filter(cust::id.eq(&p.customer_id.unwrap()))
122 .limit(1)
123 .first::<Customer>(&conn)
124 .unwrap()
125 .username
126 .clone();
127
128 ProductRating {
129 comment_text: p.comment_text,
130 comment_date: p.comment_date.unwrap(),
131 product_name: selected_product,
132 customer_name: selected_customer,
133 stars: p.stars,
134 }
135 })
136 .collect::<Vec<_>>();
137 return HttpResponse::Ok().json(&json_ratings);
98} 138}