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

parent_id support #225

Merged
merged 1 commit into from
Aug 23, 2024
Merged
Show file tree
Hide file tree
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
3 changes: 2 additions & 1 deletion src/api/handlers/asset/asset_table_api_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,9 @@ pub async fn asset_table_api_handler(
return Err(Error::Forbidden);
}

let parent_id = query_param.parent_id.unwrap_or_default();
let current_page = query_param.page.unwrap_or(1);
let asset_pagination = state.asset_service.paginate(&state.db, current_page).await?;
let asset_pagination = state.asset_service.paginate(&state.db, current_page, parent_id).await?;

Ok(Json(asset_pagination))
}
4 changes: 3 additions & 1 deletion src/api/handlers/asset/create_folder_api_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,11 @@ pub async fn create_folder_api_handler(
return Err(Error::BadRequestError(error_response));
}

let parent_id = payload.parent_id.unwrap_or_default();

let created_asset_folder = state
.asset_service
.create_asset_folder(&state.db, payload.name, logged_in_user)
.create_asset_folder(&state.db, payload.name, parent_id, logged_in_user)
.await?;

let created_response = ApiResponse {
Expand Down
1 change: 1 addition & 0 deletions src/api/handlers/asset/request/create_folder_request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use crate::models::validation_error::{ErrorMessage, Validate};
#[derive(Deserialize, Debug, Clone)]
pub struct CreateFolderRequest {
pub name: String,
pub parent_id: Option<String>
}

impl CreateFolderRequest {
Expand Down
3 changes: 2 additions & 1 deletion src/api/handlers/asset/request/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
pub mod create_folder_request;
pub mod rename_asset_request;
pub mod rename_asset_request;
pub mod store_asset_request;
6 changes: 6 additions & 0 deletions src/api/handlers/asset/request/store_asset_request.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
use serde::Deserialize;

#[derive(Deserialize, Debug, Clone)]
pub struct StoreAssetRequest {
pub parent_id: Option<String>
}
25 changes: 19 additions & 6 deletions src/api/handlers/asset/store_asset_api_handler.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
use std::path::Path;
use std::sync::Arc;

use crate::{
avored_state::AvoRedState,
error::Result
};
use axum::{Extension, extract::State, Json, response::IntoResponse};
use axum::extract::Multipart;
use axum::extract::{Multipart, Query};
use rand::distributions::Alphanumeric;
use rand::Rng;
use serde::Serialize;
use crate::api::handlers::asset::request::store_asset_request::StoreAssetRequest;
use crate::error::Error;
use crate::models::asset_model::{CreatableAssetModelNew, MetaDataType, NewAssetModel};
use crate::models::token_claim_model::LoggedInUser;
Expand All @@ -19,6 +19,7 @@ const ALLOW_TYPES: [&str; 3] = ["image/jpeg", "image/jpg", "image/png"];
pub async fn store_asset_api_handler(
Extension(logged_in_user): Extension<LoggedInUser>,
state: State<Arc<AvoRedState>>,
Query(query_param): Query<StoreAssetRequest>,
mut multipart: Multipart,
) -> Result<impl IntoResponse> {
println!("->> {:<12} - store_asset_api_handler", "HANDLER");
Expand Down Expand Up @@ -65,16 +66,28 @@ pub async fn store_asset_api_handler(
if !file_name.is_empty() {
let file_ext = file_name.split('.').last().unwrap_or(".png");
let new_file_name = format!("{}.{}", s, file_ext);
let query_parent_id = query_param.parent_id.clone().unwrap_or_default();
let asset_file;

let file_name = Path::new(&new_file_name).file_name().unwrap();
if !query_parent_id.is_empty() {
let parent_asset = &state
.asset_service
.find_by_id(&state.db, &query_parent_id)
.await?;

asset_file = format!("{}/{}", parent_asset.path, new_file_name.clone());
} else {
asset_file = format!("public/upload/{}", new_file_name.clone());
}

let asset_file = format!("public/upload/{}", new_file_name.clone());
creatable_asset_model.name = new_file_name.clone();
creatable_asset_model.path = asset_file;
creatable_asset_model.path = asset_file.clone();
creatable_asset_model.asset_type = String::from("FILE");
creatable_asset_model.metadata = MetaDataType::FileTypeMetaData {file_type};

let full_path = Path::new("public").join("upload").join(file_name);
let full_path = format!("./{}", asset_file);


tokio::fs::write(full_path, data).await?;
}
},
Expand Down
1 change: 1 addition & 0 deletions src/api/handlers/page/request/page_table_request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@ use serde::Deserialize;
pub struct PageTableRequest {
pub page: Option<i64>,
pub order: Option<String>,
pub parent_id: Option<String>,
}
6 changes: 4 additions & 2 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,14 +36,16 @@ impl core::fmt::Display for Error {
impl std::error::Error for Error {}

impl From<serde_json::Error> for Error {
fn from(_val: serde_json::Error) -> Self {
fn from(val: serde_json::Error) -> Self {
error!("there is an issue with serde json error: {val:?}");
Error::Generic("Serde struct to string Error".to_string())
}
}


impl From<std::io::Error> for Error {
fn from(_val: std::io::Error) -> Self {
fn from(val: std::io::Error) -> Self {
error!("there is an issue with creating io error: {val:?}");
Error::Generic("tokio file create folder error ".to_string())
}
}
Expand Down
20 changes: 16 additions & 4 deletions src/repositories/asset_repository.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,23 @@
datastore: &Datastore,
database_session: &Session,
start: i64,
parent_id: String
) -> Result<Vec<NewAssetModel>> {
let sql = "SELECT * FROM type::table($table) LIMIT $limit START $start;";
let vars = BTreeMap::from([
let sql;

Check warning

Code scanning / clippy

unneeded late initialization Warning

unneeded late initialization
let vars;

Check warning

Code scanning / clippy

unneeded late initialization Warning

unneeded late initialization

// @todo fix this one

sql = "SELECT * FROM type::table($table) WHERE parent_id=$parent_id LIMIT $limit START $start;";

Check warning

Code scanning / clippy

unneeded late initialization Warning

unneeded late initialization
vars = BTreeMap::from([
("limit".into(), PER_PAGE.into()),
("start".into(), start.into()),
("table".into(), ASSET_TABLE.into()),
("parent_id".into(), parent_id.into()),
]);

Check warning

Code scanning / clippy

unneeded late initialization Warning

unneeded late initialization



let responses = datastore.execute(sql, database_session, Some(vars)).await?;

let mut asset_list: Vec<NewAssetModel> = Vec::new();
Expand All @@ -48,9 +58,11 @@
&self,
datastore: &Datastore,
database_session: &Session,
parent_id: String
) -> Result<ModelCount> {
let sql = "SELECT count() FROM assets GROUP ALL;";
let responses = datastore.execute(sql, database_session, None).await?;
let sql = format!("SELECT count() FROM assets WHERE parent_id = '{}' GROUP ALL;", parent_id);

let responses = datastore.execute(&sql, database_session, None).await?;

let result_object_option = into_iter_objects(responses)?.next();
let result_object = match result_object_option {
Expand Down
30 changes: 19 additions & 11 deletions src/services/asset_service.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use std::path::Path;
use crate::{error::Result, PER_PAGE, providers::avored_database_provider::DB, repositories::asset_repository::AssetRepository};
use crate::models::asset_model::{AssetPagination, CreatableAssetModelNew, MetaDataType, NewAssetModel};
use crate::models::Pagination;
Expand All @@ -18,13 +17,14 @@ impl AssetService {
&self,
(datastore, database_session): &DB,
current_page: i64,
parent_id: String
) -> Result<AssetPagination> {
let start = (current_page - 1) * PER_PAGE;
let to = start + PER_PAGE;

let asset_model_count = self
.asset_repository
.get_total_count(datastore, database_session)
.get_total_count(datastore, database_session, parent_id.clone())
.await?;

let mut has_next_page = false;
Expand All @@ -50,7 +50,7 @@ impl AssetService {

let assets = self
.asset_repository
.paginate(datastore, database_session, start)
.paginate(datastore, database_session, start, parent_id)
.await?;

Ok(AssetPagination {
Expand Down Expand Up @@ -101,24 +101,32 @@ impl AssetService {

pub async fn create_asset_folder(
&self,
(datastore, database_session): &DB,
db: &DB,
name: String,
parent_id: String,
logged_in_user: LoggedInUser
) -> Result<NewAssetModel> {
let (datastore, database_session) = db;

let mut full_path = format!("public/upload/{}", name.clone());

if !parent_id.is_empty() {
let asset = self
.find_by_id(db, &parent_id)
.await?;

let full_path = Path::new("public").join("upload").join(name.clone());
// @todo createa folder in file system here...
tokio::fs::create_dir_all(full_path).await?;
full_path = format!("{}/{}",asset.path, name.clone());
}
tokio::fs::create_dir_all(&format!("./{}", full_path.clone())).await?;

// @todo if we have a parent_id then use the path from parent_id to build a new path
let relative_path = format!("/public/upload/{}", name);
// @todo fix this default color????
let color= String::from("text-gray-400");

let creatable_asset_model = CreatableAssetModelNew {
logged_in_username: logged_in_user.email,
parent_id: "".to_string(),
parent_id,
name: name.clone(),
path: relative_path,
path: full_path,
asset_type: "FOLDER".to_string(),
metadata: MetaDataType::FolderTypeMetaData {color},
};
Expand Down
Loading