🎨 Y añade pub_config!()

This commit is contained in:
Manuel Cillero 2022-11-10 21:14:57 +01:00
parent 680a61247a
commit 885710e0c3
5 changed files with 73 additions and 105 deletions

View file

@ -24,6 +24,7 @@ categories = [
[dependencies]
async-trait = "0.1.58"
concat-string = "1.0.1"
doc-comment = "0.3.3"
figlet-rs = "0.1.4"
futures = "0.3.25"
nom = "7.1.1"

View file

@ -1,8 +1,6 @@
//! Ajustes globales de la configuración.
use crate::config;
use crate::predefined_settings;
use crate::LazyStatic;
use crate::pub_config;
use serde::Deserialize;
@ -53,9 +51,9 @@ pub struct Database {
pub db_pass: String,
/// Valor predefinido: *"localhost"*
pub db_host: String,
/// Valor predefinido: *"0"*
/// Valor predefinido: *0*
pub db_port: u16,
/// Valor predefinido: *"5"*
/// Valor predefinido: *5*
pub max_pool_size: u32,
}
@ -92,24 +90,11 @@ pub struct Log {
pub struct Server {
/// Valor predefinido: *"localhost"*
pub bind_address: String,
/// Valor predefinido: *"8088"*
/// Valor predefinido: *8088*
pub bind_port: u16,
}
/// Declara y asigna los valores predefinidos de los ajustes globales para la estructura
/// [`Settings`].
///
/// ```
/// use pagetop::prelude::*;
///
/// fn demo() {
/// println!("App name: {}", &SETTINGS.app.name);
/// println!("App description: {}", &SETTINGS.app.description);
/// println!("Value of PAGETOP_RUN_MODE: {}", &SETTINGS.app.run_mode);
/// }
/// ```
pub static SETTINGS: LazyStatic<Settings> = LazyStatic::new(|| {
config::try_into::<Settings>(predefined_settings!(
pub_config!(SETTINGS: Settings,
// [app]
"app.name" => "PageTop Application",
"app.description" => "Developed with the amazing PageTop framework.",
@ -124,8 +109,8 @@ pub static SETTINGS: LazyStatic<Settings> = LazyStatic::new(|| {
"database.db_user" => "",
"database.db_pass" => "",
"database.db_host" => "localhost",
"database.db_port" => "0",
"database.max_pool_size" => "5",
"database.db_port" => 0,
"database.max_pool_size" => 5,
// [dev]
"dev.static_files" => "",
@ -139,6 +124,5 @@ pub static SETTINGS: LazyStatic<Settings> = LazyStatic::new(|| {
// [server]
"server.bind_address" => "localhost",
"server.bind_port" => "8088"
))
});
"server.bind_port" => 8088,
);

View file

@ -50,9 +50,8 @@
//! serde = { version = "1.0", features = ["derive"] }
//! ```
//!
//! Y luego declara con [`LazyStatic`] tus ajustes, usando tipos seguros mediante
//! [`config::try_into<S>()`](try_into) y asignando los valores predefinidos directamente con la
//! macro [`predefined_settings!`](crate::predefined_settings) para la estructura asociada:
//! Y luego declara con la macro [`pub_config!`](crate::pub_config) tus ajustes, usando tipos
//! seguros y asignando los valores predefinidos para la estructura asociada:
//!
//! ```
//! use pagetop::prelude::*;
@ -71,14 +70,12 @@
//! pub height: u16,
//! }
//!
//! pub static MY_SETTINGS: LazyStatic<MySettings> = LazyStatic::new(|| {
//! config::try_into::<MySettings>(predefined_settings!(
//! pub_config!(MY_SETTINGS: MySettings,
//! // [myapp]
//! "myapp.name" => "Value Name",
//! "myapp.width" => "900",
//! "myapp.height" => "320"
//! ))
//! });
//! "myapp.width" => 900,
//! "myapp.height" => 320,
//! );
//! ```
//!
//! De hecho, así se declaran los ajustes globales de la configuración (ver
@ -100,7 +97,15 @@
//! # Cómo usar tus nuevos ajustes de configuración
//!
//! ```
//! fn demo() {
//! use pagetop::prelude::*;
//!
//! fn global_settings() {
//! println!("App name: {}", &SETTINGS.app.name);
//! println!("App description: {}", &SETTINGS.app.description);
//! println!("Value of PAGETOP_RUN_MODE: {}", &SETTINGS.app.run_mode);
//! }
//!
//! fn module_settings() {
//! println!("{} - {:?}", &MY_SETTINGS.myapp.name, &MY_SETTINGS.myapp.description);
//! println!("{}", &MY_SETTINGS.myapp.width);
//! }
@ -119,39 +124,14 @@ use crate::LazyStatic;
use crate::config::data::ConfigData;
use crate::config::file::File;
use std::collections::HashMap;
use std::env;
use serde::Deserialize;
/// Un *HashMap* con una lista de literales `"clave" => "valor"` para asignar ajustes de
/// configuración predefinidos.
///
/// Ver [`cómo añadir ajustes de configuración`](index.html#cómo-añadir-ajustes-de-configuración).
pub type PredefinedSettings = HashMap<&'static str, &'static str>;
#[macro_export]
/// Macro para crear e inicializar un *HashMap* ([`PredefinedSettings`]) con una lista de literales
/// `"clave" => "valor"` para asignar los ajustes de configuración predefinidos.
///
/// Ver [`cómo añadir ajustes de configuración`](config/index.html#cómo-añadir-ajustes-de-configuración).
macro_rules! predefined_settings {
( $($key:literal => $value:literal),* ) => {{
#[allow(unused_mut)]
let mut a = $crate::config::PredefinedSettings::new();
$(
a.insert($key, $value);
)*
a
}};
}
/// Directorio donde se encuentran los archivos de configuración.
const CONFIG_DIR: &str = "config";
/// Todos los valores originales de la configuración en forma de pares `clave = valor` recogidos de
/// los archivos de configuración.
static CONFIG_DATA: LazyStatic<ConfigData> = LazyStatic::new(|| {
pub static CONFIG: LazyStatic<ConfigData> = LazyStatic::new(|| {
// Modo de ejecución según la variable de entorno PAGETOP_RUN_MODE. Por defecto 'default'.
let run_mode = env::var("PAGETOP_RUN_MODE").unwrap_or_else(|_| "default".into());
@ -176,22 +156,27 @@ static CONFIG_DATA: LazyStatic<ConfigData> = LazyStatic::new(|| {
settings
});
/// Asigna los ajustes de configuración de tu módulo usando tipos seguros y valores predefinidos
/// para la estructura asociada S.
#[macro_export]
/// Asigna los ajustes de configuración de tu módulo usando tipos seguros y valores predefinidos.
///
/// Detiene la aplicación con un panic! si no pueden asignarse los ajustes de configuración.
///
/// Ver [`Cómo añadir ajustes de configuración`](index.html#cómo-añadir-ajustes-de-configuración).
pub fn try_into<S>(values: PredefinedSettings) -> S
where
S: Deserialize<'static>,
{
let mut settings = CONFIG_DATA.clone();
for (key, value) in values.iter() {
settings.set_default(key, *value).unwrap();
}
/// Ver [`Cómo añadir ajustes de configuración`](config/index.html#cómo-añadir-ajustes-de-configuración).
macro_rules! pub_config {
( $S:ident: $t:ty $(, $k:literal => $v:literal)*$(,)* ) => { crate::doc_comment! {
concat!(
"Declara y asigna los valores predefinidos para los ajustes de configuración ",
"asociados a la estructura [`", stringify!($t), "`]."
),
pub static $S: $crate::LazyStatic<$t> = $crate::LazyStatic::new(|| {
let mut settings = $crate::config::CONFIG.clone();
$(
settings.set_default($k, $v).unwrap();
)*
match settings.try_into() {
Ok(s) => s,
Err(e) => panic!("Error parsing settings: {}", e),
}
});
}};
}

View file

@ -40,11 +40,11 @@
// GLOBAL.
pub use concat_string::concat_string;
pub use doc_comment::doc_comment;
pub use once_cell::sync::Lazy as LazyStatic;
// LOCAL.
#[allow(unused_imports)]
pub(crate) use futures::executor::block_on as run_now;
// APIs PÚBLICAS.

View file

@ -2,9 +2,7 @@
pub use crate::{concat_string, LazyStatic};
// Macros.
pub use crate::{
args, configure_service_for_static_files, predefined_settings, pub_handle, pub_locale,
};
pub use crate::{args, configure_service_for_static_files, pub_config, pub_handle, pub_locale};
// Helpers.
pub use crate::util;