From d66063a1f774bd01fe15d61f10d16f85fa08cec4 Mon Sep 17 00:00:00 2001 From: Manuel Cillero Date: Mon, 26 Feb 2024 07:39:08 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=A5=20Remove=20unwrap=20usage=20to=20i?= =?UTF-8?q?mprove=20new=20apps=20setup?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- drust/src/main.rs | 2 +- examples/hello-name.rs | 2 +- examples/hello-world.rs | 2 +- src/app.rs | 129 ++++++++++++++++++++--------------- src/lib.rs | 2 +- tests/server/health_check.rs | 2 +- 6 files changed, 79 insertions(+), 60 deletions(-) diff --git a/drust/src/main.rs b/drust/src/main.rs index d1381154..a1e831f2 100644 --- a/drust/src/main.rs +++ b/drust/src/main.rs @@ -25,5 +25,5 @@ impl PackageTrait for Drust { #[pagetop::main] async fn main() -> std::io::Result<()> { - Application::prepare(&Drust).unwrap().run()?.await + Application::prepare(&Drust).run()?.await } diff --git a/examples/hello-name.rs b/examples/hello-name.rs index dab31818..c73cd330 100644 --- a/examples/hello-name.rs +++ b/examples/hello-name.rs @@ -21,5 +21,5 @@ async fn hello_name( #[pagetop::main] async fn main() -> std::io::Result<()> { - Application::prepare(&HelloName).unwrap().run()?.await + Application::prepare(&HelloName).run()?.await } diff --git a/examples/hello-world.rs b/examples/hello-world.rs index eb7ef636..b1ec2609 100644 --- a/examples/hello-world.rs +++ b/examples/hello-world.rs @@ -16,5 +16,5 @@ async fn hello_world(request: service::HttpRequest) -> ResultPage std::io::Result<()> { - Application::prepare(&HelloWorld).unwrap().run()?.await + Application::prepare(&HelloWorld).run()?.await } diff --git a/src/app.rs b/src/app.rs index f69dcff2..9d30f421 100644 --- a/src/app.rs +++ b/src/app.rs @@ -21,43 +21,86 @@ use std::io::Error; pub struct Application; impl Application { - pub fn prepare(app: PackageRef) -> Result { - // On startup. - show_banner(); + /// Creates a new application instance without any package. + pub fn new() -> Self { + Self::internal_prepare(None) + } - // Inicia registro de trazas y eventos. + /// Prepares an application instance with a specific package. + pub fn prepare(app: PackageRef) -> Self { + Self::internal_prepare(Some(app)) + } + + // Internal method to prepare the application, optionally with a package. + fn internal_prepare(app: Option) -> Self { + // On startup, show the application banner. + Self::show_banner(); + + // Starts logging and event tracing. LazyStatic::force(&trace::TRACING); - // Valida el identificador global de idioma. + // Validates the global language identifier. LazyStatic::force(&locale::LANGID); #[cfg(feature = "database")] - // Conecta con la base de datos. + // Connects to the database. LazyStatic::force(&db::DBCONN); - // Registra los paquetes de la aplicación. - package::all::register_packages(app); + // Registers the application's packages. + if let Some(app) = app { + package::all::register_packages(app); + } - // Registra acciones de los paquetes. + // Registers package actions. package::all::register_actions(); - // Inicializa los paquetes. + // Initializes the packages. package::all::init_packages(); #[cfg(feature = "database")] - // Ejecuta actualizaciones pendientes de la base de datos. + // Runs pending database migrations. package::all::run_migrations(); - Ok(Self) + Self } + // Displays the application banner based on the configuration. + fn show_banner() { + if config::SETTINGS.app.startup_banner.to_lowercase() != "off" { + // Application name, formatted for the terminal width if necessary. + let mut app_name = config::SETTINGS.app.name.to_string(); + if let Some((term_width, _)) = term_size::dimensions() { + if term_width >= 80 { + let maxlen = (term_width / 10) - 2; + let mut app = app_name.substring(0, maxlen).to_owned(); + if app_name.len() > maxlen { + app = format!("{}...", app); + } + if let Some(ff) = figfont::FIGFONT.convert(&app) { + app_name = ff.to_string(); + } + } + } + println!("\n{}", app_name); + + // Application description. + if !config::SETTINGS.app.description.is_empty() { + println!("{}\n", config::SETTINGS.app.description); + }; + + // PageTop version. + println!("Powered by PageTop {}\n", env!("CARGO_PKG_VERSION")); + } + } + + /// Starts the web server. pub fn run(self) -> Result { - // Generate cookie key. + // Generate the cookie key. let secret_key = service::cookie::Key::generate(); - // Prepara el servidor web. + // Prepares the web server. Ok(service::HttpServer::new(move || { - service_app() + Self::service_app() .wrap(tracing_actix_web::TracingLogger::default()) .wrap( SessionMiddleware::builder(CookieSessionStore::default(), secret_key.clone()) @@ -82,6 +125,7 @@ impl Application { .run()) } + /// Method for testing, returns a service application instance. pub fn test( self, ) -> service::App< @@ -93,50 +137,25 @@ impl Application { InitError = (), >, > { - service_app() + Self::service_app() } -} -fn service_app() -> service::App< - impl service::Factory< - service::Request, - Config = (), - Response = service::Response, - Error = service::Error, - InitError = (), - >, -> { - service::App::new() - .configure(package::all::configure_services) - .default_service(service::web::route().to(service_not_found)) + // Configures the service application. + fn service_app() -> service::App< + impl service::Factory< + service::Request, + Config = (), + Response = service::Response, + Error = service::Error, + InitError = (), + >, + > { + service::App::new() + .configure(package::all::configure_services) + .default_service(service::web::route().to(service_not_found)) + } } async fn service_not_found(request: service::HttpRequest) -> ResultPage { Err(ErrorPage::NotFound(request)) } - -fn show_banner() { - if config::SETTINGS.app.startup_banner.to_lowercase() != "off" { - // Application name. - let mut app_name = config::SETTINGS.app.name.to_string(); - if let Some((term_width, _)) = term_size::dimensions() { - if term_width >= 80 { - let maxlen = (term_width / 10) - 2; - let mut app = app_name.substring(0, maxlen).to_owned(); - if app_name.len() > maxlen { - app = format!("{}...", app); - } - app_name = figfont::FIGFONT.convert(&app).unwrap().to_string(); - } - } - println!("\n{}", app_name); - - // Application description. - if !config::SETTINGS.app.description.is_empty() { - println!("{}\n", config::SETTINGS.app.description); - }; - - // PageTop version. - println!("Powered by PageTop {}\n", env!("CARGO_PKG_VERSION")); - } -} diff --git a/src/lib.rs b/src/lib.rs index d93827c7..957bf3e9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -48,7 +48,7 @@ //! //! #[pagetop::main] //! async fn main() -> std::io::Result<()> { -//! Application::prepare(&HelloWorld).unwrap().run()?.await +//! Application::prepare(&HelloWorld).run()?.await //! } //! ``` //! This program implements a package named `HelloWorld` with one service that returns a web page diff --git a/tests/server/health_check.rs b/tests/server/health_check.rs index 49fc7545..578ffc66 100644 --- a/tests/server/health_check.rs +++ b/tests/server/health_check.rs @@ -6,7 +6,7 @@ impl PackageTrait for HealthCheck {} #[pagetop::test] async fn health_check_works() { - let app = service::test::init_service(Application::prepare(&HealthCheck).unwrap().test()).await; + let app = service::test::init_service(Application::prepare(&HealthCheck).test()).await; let req = service::test::TestRequest::get().uri("/").to_request(); let _resp = service::test::call_service(&app, req).await;