Skip to content

Commit

Permalink
Add file service
Browse files Browse the repository at this point in the history
  • Loading branch information
marshallku committed Sep 5, 2024
1 parent c4d3703 commit da542a0
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 20 deletions.
24 changes: 4 additions & 20 deletions src/controllers/files.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,30 +2,14 @@ use axum::{
extract::{Path, State},
response::IntoResponse,
};
use reqwest::StatusCode;
use std::path::PathBuf;
use tracing::error;

use crate::{
constants::CDN_ROOT,
env::state::AppState,
utils::{
fetch::fetch_and_cache,
http::{response_error, response_file},
},
env::state::AppState, services::file::process_file_request, utils::http::response_error,
};

pub async fn get(State(state): State<AppState>, Path(path): Path<String>) -> impl IntoResponse {
let file_path = PathBuf::from(format!("{}/files/{}", CDN_ROOT, path));

if file_path.exists() {
error!("File exists but respond with Rust: {:?}", file_path);
return response_file(&file_path).await;
}

if let Err(_) = fetch_and_cache(state.host, &file_path, &path).await {
return response_error(StatusCode::NOT_FOUND);
match process_file_request(&state, &path).await {
Ok(response) => response,
Err(status) => response_error(status),
}

response_file(&file_path).await
}
25 changes: 25 additions & 0 deletions src/services/file.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
use axum::response::Response;
use reqwest::StatusCode;
use std::path::PathBuf;
use tracing::error;

use crate::{
constants::CDN_ROOT,
env::state::AppState,
utils::{fetch::fetch_and_cache, http::response_file},
};

pub async fn process_file_request(state: &AppState, path: &str) -> Result<Response, StatusCode> {
let file_path = PathBuf::from(format!("{}/files/{}", CDN_ROOT, path));

if file_path.exists() {
error!("File exists but respond with Rust: {:?}", file_path);
return Ok(response_file(&file_path).await);
}

if let Err(_) = fetch_and_cache(state.host.clone(), &file_path, &path).await {
return Err(StatusCode::NOT_FOUND);
}

Ok(response_file(&file_path).await)
}
1 change: 1 addition & 0 deletions src/services/mod.rs
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
pub mod file;
pub mod image;

0 comments on commit da542a0

Please sign in to comment.