From 0b57f140cb3cc372d8847fe4adc733c81788a85d Mon Sep 17 00:00:00 2001 From: "D. Scott Boggs" Date: Sun, 11 Jun 2023 08:56:20 -0400 Subject: [PATCH] Add static file server to rocket & SPA index redirect --- .gitignore | 2 ++ Makefile | 17 +++++++++++++++++ server/Dockerfile | 1 + server/src/api/mod.rs | 13 +++++++++++++ server/src/error.rs | 2 ++ 5 files changed, 35 insertions(+) create mode 100644 Makefile diff --git a/.gitignore b/.gitignore index 281ea43..48ad049 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,5 @@ **/target **/*.pw +python-venv/ +tickmate-backup-20230524.db diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..029f165 --- /dev/null +++ b/Makefile @@ -0,0 +1,17 @@ + +all: start-server + +client/dist/index.html: + cd client; yarn && yarn build + +build-client: client/dist/index.html + +server/public/: client/dist/index.html + rsync -a client/dist/ server/public/ + +start-server: server/public/ + docker compose up --build -d + +clean: + docker compose down + rm -r server/public/ client/dist/ diff --git a/server/Dockerfile b/server/Dockerfile index 318d74d..07f1cbb 100644 --- a/server/Dockerfile +++ b/server/Dockerfile @@ -8,4 +8,5 @@ ADD src/ src/ RUN rm dummy.rs &&\ sed -i "s:dummy.rs:src/main.rs:" Cargo.toml RUN cargo build --release +ADD public/ public/ CMD ["target/release/kalkulog-server"] diff --git a/server/src/api/mod.rs b/server/src/api/mod.rs index 7080be8..af68032 100644 --- a/server/src/api/mod.rs +++ b/server/src/api/mod.rs @@ -6,18 +6,29 @@ mod tracks; use std::default::default; use std::net::{IpAddr, Ipv4Addr}; +use rocket::fs::{FileServer, NamedFile}; use rocket::Config; use sea_orm::DatabaseConnection; +use crate::error::Error; use crate::rocket::{Build, Rocket}; pub(crate) use error::ErrorResponder; +use self::error::ApiResult; + #[get("/status")] fn status() -> &'static str { "Ok" } +#[catch(404)] +async fn spa_index_redirect() -> ApiResult { + Ok(NamedFile::open("/src/public/index.html") + .await + .map_err(Error::from)?) +} + pub(crate) fn start_server(db: DatabaseConnection) -> Rocket { use groups::*; use ticks::*; @@ -27,6 +38,7 @@ pub(crate) fn start_server(db: DatabaseConnection) -> Rocket { address: IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), ..default() }) + .register("/", catchers![spa_index_redirect]) .manage(db) .mount("/api/v1", routes![status]) .mount( @@ -41,4 +53,5 @@ pub(crate) fn start_server(db: DatabaseConnection) -> Rocket { "/api/v1/groups", routes![all_groups, group, insert_group, update_group, delete_group], ) + .mount("/", FileServer::from("/src/public")) } diff --git a/server/src/error.rs b/server/src/error.rs index 19a7ddf..f838c05 100644 --- a/server/src/error.rs +++ b/server/src/error.rs @@ -6,6 +6,8 @@ pub enum Error { Builder(#[from] UninitializedFieldError), #[error(transparent)] SeaOrm(#[from] sea_orm::DbErr), + #[error(transparent)] + Io(#[from] std::io::Error), } pub type Result = std::result::Result;