From f467472fabeaa20ad175c1c32681405ad0471fcd Mon Sep 17 00:00:00 2001 From: Artemy Date: Tue, 26 Jul 2022 20:42:16 +0300 Subject: [PATCH] feat: get rating of app method (OS-21) --- src/core.rs | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ src/main.rs | 1 + src/routes.rs | 9 +++++++++ 3 files changed, 61 insertions(+) diff --git a/src/core.rs b/src/core.rs index c4ec6f9..ddca58b 100644 --- a/src/core.rs +++ b/src/core.rs @@ -61,6 +61,57 @@ impl Core { } } + pub async fn get_rating(&self, app_name_id: &String) -> serde_json::Value { + let result = self + .reviews + .aggregate( + [ + doc! {"$match":{"app_name_id":app_name_id}}, + doc! { + "$group": { + "_id": "$app_name_id", + "rating": { + "$avg": "$score" + }, + }, + }, + ], + None, + ) + .await; + + match result { + Ok(mut result) => match result.next().await { + Some(result) => match result { + Ok(result) => { + json! ({ + "code":"ok_body", + "body":result + }) + } + Err(_) => { + json! ({ + "code":"err", + "msg":"Unknown error" + }) + } + }, + None => { + json! ({ + "code":"denied", + "msg":"This app does not exist" + }) + } + }, + Err(_) => { + json! ({ + "code":"err", + "msg":"Unknown error" + }) + } + } + } + pub async fn get_reviews(&self, app_name_id: &String) -> Vec { self.get_collection_with_params(&self.reviews, doc! {"app_name_id":app_name_id}) .await diff --git a/src/main.rs b/src/main.rs index 253e4bd..ba8be10 100644 --- a/src/main.rs +++ b/src/main.rs @@ -83,6 +83,7 @@ async fn main() -> std::io::Result<()> { .service(routes::apps) .service(routes::app) .service(routes::reviews) + .service(routes::rating) .service(routes::update) .service(routes::change_password) .service(routes::write_review), diff --git a/src/routes.rs b/src/routes.rs index 50d9945..9b9d22c 100644 --- a/src/routes.rs +++ b/src/routes.rs @@ -30,6 +30,15 @@ pub async fn reviews( HttpResponse::Ok().json(app_data.core.get_reviews(&app_name_id).await) } +#[get("/rating/{app_name_id}")] +#[has_any_permission("user", "admin")] +pub async fn rating( + app_data: web::Data, + app_name_id: web::Path, +) -> impl Responder { + response(app_data.core.get_rating(&app_name_id).await) +} + #[get("/app/{name}")] #[has_any_permission("user", "admin")] pub async fn app(app_data: web::Data, name: web::Path) -> impl Responder {