🎨 Y añade pub_config!()
This commit is contained in:
parent
680a61247a
commit
885710e0c3
5 changed files with 73 additions and 105 deletions
|
|
@ -24,6 +24,7 @@ categories = [
|
||||||
[dependencies]
|
[dependencies]
|
||||||
async-trait = "0.1.58"
|
async-trait = "0.1.58"
|
||||||
concat-string = "1.0.1"
|
concat-string = "1.0.1"
|
||||||
|
doc-comment = "0.3.3"
|
||||||
figlet-rs = "0.1.4"
|
figlet-rs = "0.1.4"
|
||||||
futures = "0.3.25"
|
futures = "0.3.25"
|
||||||
nom = "7.1.1"
|
nom = "7.1.1"
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,6 @@
|
||||||
//! Ajustes globales de la configuración.
|
//! Ajustes globales de la configuración.
|
||||||
|
|
||||||
use crate::config;
|
use crate::pub_config;
|
||||||
use crate::predefined_settings;
|
|
||||||
use crate::LazyStatic;
|
|
||||||
|
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
|
@ -53,9 +51,9 @@ pub struct Database {
|
||||||
pub db_pass: String,
|
pub db_pass: String,
|
||||||
/// Valor predefinido: *"localhost"*
|
/// Valor predefinido: *"localhost"*
|
||||||
pub db_host: String,
|
pub db_host: String,
|
||||||
/// Valor predefinido: *"0"*
|
/// Valor predefinido: *0*
|
||||||
pub db_port: u16,
|
pub db_port: u16,
|
||||||
/// Valor predefinido: *"5"*
|
/// Valor predefinido: *5*
|
||||||
pub max_pool_size: u32,
|
pub max_pool_size: u32,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -92,53 +90,39 @@ pub struct Log {
|
||||||
pub struct Server {
|
pub struct Server {
|
||||||
/// Valor predefinido: *"localhost"*
|
/// Valor predefinido: *"localhost"*
|
||||||
pub bind_address: String,
|
pub bind_address: String,
|
||||||
/// Valor predefinido: *"8088"*
|
/// Valor predefinido: *8088*
|
||||||
pub bind_port: u16,
|
pub bind_port: u16,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Declara y asigna los valores predefinidos de los ajustes globales para la estructura
|
pub_config!(SETTINGS: Settings,
|
||||||
/// [`Settings`].
|
// [app]
|
||||||
///
|
"app.name" => "PageTop Application",
|
||||||
/// ```
|
"app.description" => "Developed with the amazing PageTop framework.",
|
||||||
/// use pagetop::prelude::*;
|
"app.theme" => "Bootsier",
|
||||||
///
|
"app.language" => "en-US",
|
||||||
/// fn demo() {
|
"app.direction" => "ltr",
|
||||||
/// println!("App name: {}", &SETTINGS.app.name);
|
"app.startup_banner" => "Slant",
|
||||||
/// 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!(
|
|
||||||
// [app]
|
|
||||||
"app.name" => "PageTop Application",
|
|
||||||
"app.description" => "Developed with the amazing PageTop framework.",
|
|
||||||
"app.theme" => "Bootsier",
|
|
||||||
"app.language" => "en-US",
|
|
||||||
"app.direction" => "ltr",
|
|
||||||
"app.startup_banner" => "Slant",
|
|
||||||
|
|
||||||
// [database]
|
// [database]
|
||||||
"database.db_type" => "",
|
"database.db_type" => "",
|
||||||
"database.db_name" => "",
|
"database.db_name" => "",
|
||||||
"database.db_user" => "",
|
"database.db_user" => "",
|
||||||
"database.db_pass" => "",
|
"database.db_pass" => "",
|
||||||
"database.db_host" => "localhost",
|
"database.db_host" => "localhost",
|
||||||
"database.db_port" => "0",
|
"database.db_port" => 0,
|
||||||
"database.max_pool_size" => "5",
|
"database.max_pool_size" => 5,
|
||||||
|
|
||||||
// [dev]
|
// [dev]
|
||||||
"dev.static_files" => "",
|
"dev.static_files" => "",
|
||||||
|
|
||||||
// [log]
|
// [log]
|
||||||
"log.tracing" => "Info",
|
"log.tracing" => "Info",
|
||||||
"log.rolling" => "Stdout",
|
"log.rolling" => "Stdout",
|
||||||
"log.path" => "log",
|
"log.path" => "log",
|
||||||
"log.prefix" => "tracing.log",
|
"log.prefix" => "tracing.log",
|
||||||
"log.format" => "Full",
|
"log.format" => "Full",
|
||||||
|
|
||||||
// [server]
|
// [server]
|
||||||
"server.bind_address" => "localhost",
|
"server.bind_address" => "localhost",
|
||||||
"server.bind_port" => "8088"
|
"server.bind_port" => 8088,
|
||||||
))
|
);
|
||||||
});
|
|
||||||
|
|
|
||||||
|
|
@ -50,9 +50,8 @@
|
||||||
//! serde = { version = "1.0", features = ["derive"] }
|
//! serde = { version = "1.0", features = ["derive"] }
|
||||||
//! ```
|
//! ```
|
||||||
//!
|
//!
|
||||||
//! Y luego declara con [`LazyStatic`] tus ajustes, usando tipos seguros mediante
|
//! Y luego declara con la macro [`pub_config!`](crate::pub_config) tus ajustes, usando tipos
|
||||||
//! [`config::try_into<S>()`](try_into) y asignando los valores predefinidos directamente con la
|
//! seguros y asignando los valores predefinidos para la estructura asociada:
|
||||||
//! macro [`predefined_settings!`](crate::predefined_settings) para la estructura asociada:
|
|
||||||
//!
|
//!
|
||||||
//! ```
|
//! ```
|
||||||
//! use pagetop::prelude::*;
|
//! use pagetop::prelude::*;
|
||||||
|
|
@ -71,14 +70,12 @@
|
||||||
//! pub height: u16,
|
//! pub height: u16,
|
||||||
//! }
|
//! }
|
||||||
//!
|
//!
|
||||||
//! pub static MY_SETTINGS: LazyStatic<MySettings> = LazyStatic::new(|| {
|
//! pub_config!(MY_SETTINGS: MySettings,
|
||||||
//! config::try_into::<MySettings>(predefined_settings!(
|
//! // [myapp]
|
||||||
//! // [myapp]
|
//! "myapp.name" => "Value Name",
|
||||||
//! "myapp.name" => "Value Name",
|
//! "myapp.width" => 900,
|
||||||
//! "myapp.width" => "900",
|
//! "myapp.height" => 320,
|
||||||
//! "myapp.height" => "320"
|
//! );
|
||||||
//! ))
|
|
||||||
//! });
|
|
||||||
//! ```
|
//! ```
|
||||||
//!
|
//!
|
||||||
//! De hecho, así se declaran los ajustes globales de la configuración (ver
|
//! 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
|
//! # 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.name, &MY_SETTINGS.myapp.description);
|
||||||
//! println!("{}", &MY_SETTINGS.myapp.width);
|
//! println!("{}", &MY_SETTINGS.myapp.width);
|
||||||
//! }
|
//! }
|
||||||
|
|
@ -119,39 +124,14 @@ use crate::LazyStatic;
|
||||||
use crate::config::data::ConfigData;
|
use crate::config::data::ConfigData;
|
||||||
use crate::config::file::File;
|
use crate::config::file::File;
|
||||||
|
|
||||||
use std::collections::HashMap;
|
|
||||||
use std::env;
|
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.
|
/// Directorio donde se encuentran los archivos de configuración.
|
||||||
const CONFIG_DIR: &str = "config";
|
const CONFIG_DIR: &str = "config";
|
||||||
|
|
||||||
/// Todos los valores originales de la configuración en forma de pares `clave = valor` recogidos de
|
/// Todos los valores originales de la configuración en forma de pares `clave = valor` recogidos de
|
||||||
/// los archivos de configuración.
|
/// 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'.
|
// 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());
|
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
|
settings
|
||||||
});
|
});
|
||||||
|
|
||||||
/// Asigna los ajustes de configuración de tu módulo usando tipos seguros y valores predefinidos
|
#[macro_export]
|
||||||
/// para la estructura asociada S.
|
/// 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.
|
/// 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).
|
/// Ver [`Cómo añadir ajustes de configuración`](config/index.html#cómo-añadir-ajustes-de-configuración).
|
||||||
pub fn try_into<S>(values: PredefinedSettings) -> S
|
macro_rules! pub_config {
|
||||||
where
|
( $S:ident: $t:ty $(, $k:literal => $v:literal)*$(,)* ) => { crate::doc_comment! {
|
||||||
S: Deserialize<'static>,
|
concat!(
|
||||||
{
|
"Declara y asigna los valores predefinidos para los ajustes de configuración ",
|
||||||
let mut settings = CONFIG_DATA.clone();
|
"asociados a la estructura [`", stringify!($t), "`]."
|
||||||
for (key, value) in values.iter() {
|
),
|
||||||
settings.set_default(key, *value).unwrap();
|
pub static $S: $crate::LazyStatic<$t> = $crate::LazyStatic::new(|| {
|
||||||
}
|
let mut settings = $crate::config::CONFIG.clone();
|
||||||
match settings.try_into() {
|
$(
|
||||||
Ok(s) => s,
|
settings.set_default($k, $v).unwrap();
|
||||||
Err(e) => panic!("Error parsing settings: {}", e),
|
)*
|
||||||
}
|
match settings.try_into() {
|
||||||
|
Ok(s) => s,
|
||||||
|
Err(e) => panic!("Error parsing settings: {}", e),
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}};
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -40,11 +40,11 @@
|
||||||
// GLOBAL.
|
// GLOBAL.
|
||||||
|
|
||||||
pub use concat_string::concat_string;
|
pub use concat_string::concat_string;
|
||||||
|
pub use doc_comment::doc_comment;
|
||||||
pub use once_cell::sync::Lazy as LazyStatic;
|
pub use once_cell::sync::Lazy as LazyStatic;
|
||||||
|
|
||||||
// LOCAL.
|
// LOCAL.
|
||||||
|
|
||||||
#[allow(unused_imports)]
|
|
||||||
pub(crate) use futures::executor::block_on as run_now;
|
pub(crate) use futures::executor::block_on as run_now;
|
||||||
|
|
||||||
// APIs PÚBLICAS.
|
// APIs PÚBLICAS.
|
||||||
|
|
|
||||||
|
|
@ -2,9 +2,7 @@
|
||||||
pub use crate::{concat_string, LazyStatic};
|
pub use crate::{concat_string, LazyStatic};
|
||||||
|
|
||||||
// Macros.
|
// Macros.
|
||||||
pub use crate::{
|
pub use crate::{args, configure_service_for_static_files, pub_config, pub_handle, pub_locale};
|
||||||
args, configure_service_for_static_files, predefined_settings, pub_handle, pub_locale,
|
|
||||||
};
|
|
||||||
|
|
||||||
// Helpers.
|
// Helpers.
|
||||||
pub use crate::util;
|
pub use crate::util;
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue