refactor: get_collection

This commit is contained in:
Artemy 2023-07-08 19:11:13 +03:00
parent b71bfca543
commit c9675fa971
2 changed files with 31 additions and 17 deletions

View file

@ -12,6 +12,8 @@ use serde_json::json;
use sha3::{Digest, Sha3_256}; use sha3::{Digest, Sha3_256};
use std::env; use std::env;
use mongodb::error::Error;
use crate::types::*; use crate::types::*;
pub struct Core { pub struct Core {
users: Collection<Document>, users: Collection<Document>,
@ -35,7 +37,7 @@ impl Core {
salt: env::var("SALT").expect("Hash salt not found"), salt: env::var("SALT").expect("Hash salt not found"),
} }
} }
pub async fn get_apps(&self) -> Vec<Document> { pub async fn get_apps(&self) -> Result<Vec<Document>, Error> {
self.get_collection(&self.apps).await self.get_collection(&self.apps).await
} }
@ -154,17 +156,17 @@ impl Core {
.unwrap(); .unwrap();
} }
pub async fn get_reviews(&self, app_id: &String) -> Vec<Document> { pub async fn get_reviews(&self, app_id: &String) -> Result<Vec<Document>, Error> {
self.get_collection_with_params(&self.reviews, doc! {"app_id":app_id}) self.get_collection_with_params(&self.reviews, doc! {"app_id":app_id})
.await .await
} }
pub async fn get_apps_by_tag(&self, info: &AppTags) -> Vec<Document> { pub async fn get_apps_by_tag(&self, info: &AppTags) -> Result<Vec<Document>, Error> {
self.get_collection_with_params(&self.apps, doc! {"tags":{"$in":&info.tags}}) self.get_collection_with_params(&self.apps, doc! {"tags":{"$in":&info.tags}})
.await .await
} }
pub async fn get_versions(&self, app_id: &String) -> Vec<Document> { pub async fn get_versions(&self, app_id: &String) -> Result<Vec<Document>, Error> {
self.get_collection_with_params_and_sort( self.get_collection_with_params_and_sort(
&self.apps_versions, &self.apps_versions,
doc! {"app_id":app_id}, doc! {"app_id":app_id},
@ -559,40 +561,43 @@ impl Core {
collection: &Collection<Document>, collection: &Collection<Document>,
params: Document, params: Document,
sort_params: Document, sort_params: Document,
) -> Vec<Document> { ) -> Result<Vec<Document>, Error> {
let options = FindOptions::builder() let options = FindOptions::builder()
.projection(doc! {"_id" : 0}) .projection(doc! {"_id" : 0})
.sort(sort_params) .sort(sort_params)
.build(); .build();
let cursor = match collection.find(params, options).await { let cursor = match collection.find(params, options).await {
Ok(cursor) => cursor, Ok(cursor) => cursor,
Err(_) => return vec![], Err(e) => return Err(e),
}; };
cursor.try_collect().await.unwrap_or_else(|_| vec![]) Ok(cursor.try_collect().await.unwrap_or_else(|_| vec![]))
} }
async fn get_collection_with_params( async fn get_collection_with_params(
&self, &self,
collection: &Collection<Document>, collection: &Collection<Document>,
params: Document, params: Document,
) -> Vec<Document> { ) -> Result<Vec<Document>, Error> {
let options = FindOptions::builder().projection(doc! {"_id" : 0}).build(); let options = FindOptions::builder().projection(doc! {"_id" : 0}).build();
let cursor = match collection.find(params, options).await { let cursor = match collection.find(params, options).await {
Ok(cursor) => cursor, Ok(cursor) => cursor,
Err(_) => return vec![], Err(e) => return Err(e),
}; };
cursor.try_collect().await.unwrap_or_else(|_| vec![]) Ok(cursor.try_collect().await.unwrap_or_else(|_| vec![]))
} }
async fn get_collection(&self, collection: &Collection<Document>) -> Vec<Document> { async fn get_collection(
&self,
collection: &Collection<Document>,
) -> Result<Vec<Document>, Error> {
let options = FindOptions::builder().projection(doc! {"_id" : 0}).build(); let options = FindOptions::builder().projection(doc! {"_id" : 0}).build();
let cursor = match collection.find(None, options).await { let cursor = match collection.find(None, options).await {
Ok(cursor) => cursor, Ok(cursor) => cursor,
Err(_) => return vec![], Err(e) => return Err(e),
}; };
cursor.try_collect().await.unwrap_or_else(|_| vec![]) Ok(cursor.try_collect().await.unwrap_or_else(|_| vec![]))
} }
} }

View file

@ -1,6 +1,8 @@
use crate::types::*; use crate::types::*;
use actix_web::{get, post, web, HttpRequest, HttpResponse, Responder}; use actix_web::{get, post, web, HttpRequest, HttpResponse, Responder};
use actix_web_grants::proc_macro::has_any_permission; use actix_web_grants::proc_macro::has_any_permission;
use bson::Document;
use mongodb::error::Error;
#[post("/signup")] #[post("/signup")]
pub async fn signup(app_data: web::Data<crate::AppState>, user: web::Json<User>) -> impl Responder { pub async fn signup(app_data: web::Data<crate::AppState>, user: web::Json<User>) -> impl Responder {
@ -18,7 +20,7 @@ pub async fn signin(
#[get("/apps")] #[get("/apps")]
#[has_any_permission("user", "admin")] #[has_any_permission("user", "admin")]
pub async fn apps(app_data: web::Data<crate::AppState>) -> impl Responder { pub async fn apps(app_data: web::Data<crate::AppState>) -> impl Responder {
HttpResponse::Ok().json(app_data.core.get_apps().await) resolve_collection(app_data.core.get_apps().await)
} }
#[post("/apps_by_tag")] #[post("/apps_by_tag")]
@ -27,7 +29,7 @@ pub async fn apps_by_tags(
app_data: web::Data<crate::AppState>, app_data: web::Data<crate::AppState>,
info: web::Json<AppTags>, info: web::Json<AppTags>,
) -> impl Responder { ) -> impl Responder {
HttpResponse::Ok().json(app_data.core.get_apps_by_tag(&info).await) resolve_collection(app_data.core.get_apps_by_tag(&info).await)
} }
#[get("/reviews/{app_id}")] #[get("/reviews/{app_id}")]
@ -36,7 +38,7 @@ pub async fn reviews(
app_data: web::Data<crate::AppState>, app_data: web::Data<crate::AppState>,
app_id: web::Path<String>, app_id: web::Path<String>,
) -> impl Responder { ) -> impl Responder {
HttpResponse::Ok().json(app_data.core.get_reviews(&app_id).await) resolve_collection(app_data.core.get_reviews(&app_id).await)
} }
#[get("/versions/{app_id}")] #[get("/versions/{app_id}")]
@ -45,7 +47,7 @@ pub async fn versions(
app_data: web::Data<crate::AppState>, app_data: web::Data<crate::AppState>,
app_id: web::Path<String>, app_id: web::Path<String>,
) -> impl Responder { ) -> impl Responder {
HttpResponse::Ok().json(app_data.core.get_versions(&app_id).await) resolve_collection(app_data.core.get_versions(&app_id).await)
} }
#[get("/rating/{app_id}")] #[get("/rating/{app_id}")]
@ -166,6 +168,13 @@ fn username(req: HttpRequest) -> String {
.to_string() .to_string()
} }
fn resolve_collection(resp: Result<Vec<Document>, Error>) -> HttpResponse {
match resp {
Ok(resp) => HttpResponse::Ok().json(resp),
Err(e) => HttpResponse::InternalServerError().json(e.to_string()),
}
}
fn response(result: serde_json::Value) -> impl Responder { fn response(result: serde_json::Value) -> impl Responder {
if result["code"] == "ok" { if result["code"] == "ok" {
HttpResponse::Ok().json(result) HttpResponse::Ok().json(result)