Refactored a few things from main into modules

This commit is contained in:
Dave
2026-02-23 11:39:22 +00:00
parent 7deacabea9
commit 1487092216
3 changed files with 112 additions and 104 deletions

View File

@@ -25,8 +25,31 @@ use poem::{Route, get, post};
use poem_openapi::OpenApiService;
use project::ProjectApi;
use settings::SettingsApi;
use std::path::{Path, PathBuf};
use std::sync::Arc;
const DEFAULT_PORT: u16 = 3001;
pub fn parse_port(value: Option<String>) -> u16 {
value
.and_then(|v| v.parse::<u16>().ok())
.unwrap_or(DEFAULT_PORT)
}
pub fn resolve_port() -> u16 {
parse_port(std::env::var("STORYKIT_PORT").ok())
}
pub fn write_port_file(dir: &Path, port: u16) -> Option<PathBuf> {
let path = dir.join(".story_kit_port");
std::fs::write(&path, port.to_string()).ok()?;
Some(path)
}
pub fn remove_port_file(path: &Path) {
let _ = std::fs::remove_file(path);
}
pub fn build_routes(ctx: AppContext) -> impl poem::Endpoint {
let ctx_arc = std::sync::Arc::new(ctx);
@@ -93,3 +116,34 @@ pub fn build_openapi_service(ctx: Arc<AppContext>) -> (ApiService, ApiService) {
(api_service, docs_service)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_port_defaults_to_3001() {
assert_eq!(parse_port(None), 3001);
}
#[test]
fn parse_port_reads_valid_value() {
assert_eq!(parse_port(Some("4200".to_string())), 4200);
}
#[test]
fn parse_port_ignores_invalid_value() {
assert_eq!(parse_port(Some("not_a_number".to_string())), 3001);
}
#[test]
fn write_and_remove_port_file() {
let tmp = tempfile::tempdir().unwrap();
let path = write_port_file(tmp.path(), 4567).expect("should write port file");
assert_eq!(std::fs::read_to_string(&path).unwrap(), "4567");
remove_port_file(&path);
assert!(!path.exists());
}
}