Skip to main content

cool_core/
lib.rs

1//! # cool-core
2//!
3//! cool-admin Rust 核心库,提供 CRUD 自动化、服务基类、控制器基类等功能。
4//!
5//! ## 功能特性
6//!
7//! - 🚀 基于 Salvo 的高性能 Web 框架集成
8//! - 🗃️ 基于 SeaORM 的多数据库支持(MySQL/PostgreSQL/SQLite)
9//! - 🔧 自动 CRUD 生成(add/delete/update/page/info/list)
10//! - 🛡️ 统一的异常处理
11//! - 📝 参数验证
12//! - 🔐 JWT 认证
13//! - 💾 Redis 缓存支持
14//! - 📡 事件系统
15//! - 🔌 模块化架构
16//!
17//! ## 快速开始
18//!
19//! ```rust,ignore
20//! use cool_core::prelude::*;
21//!
22//! // 定义实体
23//! #[derive(Clone, Debug, DeriveEntityModel, Serialize, Deserialize)]
24//! #[sea_orm(table_name = "goods")]
25//! pub struct Model {
26//!     #[sea_orm(primary_key)]
27//!     pub id: i64,
28//!     pub title: String,
29//!     pub price: Decimal,
30//!     pub create_time: DateTimeUtc,
31//!     pub update_time: DateTimeUtc,
32//! }
33//!
34//! // 定义服务
35//! pub struct GoodsService {
36//!     db: Arc<DatabaseConnection>,
37//! }
38//!
39//! // 定义控制器
40//! pub struct GoodsController {
41//!     service: GoodsService,
42//! }
43//! ```
44//!
45//! ## 模块说明
46//!
47//! - `cache`: 缓存模块,支持内存缓存和 Redis 缓存
48//! - `config`: 配置模块,定义框架配置结构
49//! - `constant`: 常量模块,定义全局常量和枚举
50//! - `controller`: 控制器模块,提供 CRUD 控制器基类
51//! - `entity`: 实体模块,定义实体 trait 和通用结构
52//! - `error`: 错误处理模块,统一的异常类型和响应
53//! - `event`: 事件模块,提供事件发布订阅机制
54//! - `middleware`: 中间件模块,包含权限、日志等中间件
55//! - `module`: 模块管理,支持模块注册和路由构建
56//! - `service`: 服务模块,提供 CRUD 服务基类
57//! - `util`: 工具模块,提供常用工具函数
58
59pub mod cache;
60#[cfg(feature = "cli")]
61pub mod cli;
62pub mod config;
63pub mod constant;
64pub mod controller;
65pub mod entity;
66pub mod eps;
67pub mod error;
68pub mod event;
69pub mod middleware;
70pub mod module;
71pub mod service;
72pub mod tag;
73pub mod util;
74
75/// 预导入模块,包含常用类型和 trait
76pub mod prelude {
77    #![allow(ambiguous_glob_reexports)]
78    // 缓存
79    pub use crate::cache::{CacheFactory, CacheStore, MemoryCache, RedisCache};
80
81    // 配置
82    pub use crate::config::*;
83
84    // 常量
85    pub use crate::constant::*;
86
87    // 控制器
88    pub use crate::controller::{BaseController, ControllerOption, CrudApi};
89
90    // 实体
91    pub use crate::entity::*;
92
93    // 错误处理
94    pub use crate::error::{CoolError, CoolResponse, CoolResult, PageResult, Pagination};
95
96    // 事件
97    pub use crate::event::{global_event_manager, EventManager};
98
99    // 中间件
100    pub use crate::middleware::{
101        authority, exception_filter, request_log, AdminInfo, AppUserInfo, AuthorityConfig,
102        DepotAppUserExt, DepotExt, ExceptionFilter, JwtClaims,
103    };
104
105    // 模块
106    pub use crate::module::{global_module_registry, Module, ModuleInfo, ModuleRegistry};
107
108    // 服务
109    pub use crate::service::{BaseService, ModifyType, SimpleService};
110
111    // 标签与 EPS
112    pub use crate::eps::{
113        global_eps_registry, ColumnInfo as EpsColumnInfo, ControllerEps, EpsRegistry, EpsScope,
114        ModuleInfo as EpsModuleInfo, QueryOpInfo as EpsQueryOpInfo, RouteInfo as EpsRouteInfo,
115    };
116    pub use crate::tag::{global_url_tag_store, TagType, UrlTagStore};
117
118    // 工具
119    pub use crate::util;
120
121    // CLI 工具
122    #[cfg(feature = "cli")]
123    pub use crate::cli::{check, clear_entities_file, generate_entities_file};
124
125    // 重导出常用依赖
126    pub use async_trait::async_trait;
127    pub use salvo::prelude::*;
128    pub use sea_orm::{
129        entity::prelude::*, ActiveModelTrait, ColumnTrait, ConnectionTrait, DatabaseConnection,
130        EntityTrait, IntoActiveModel, ModelTrait, PaginatorTrait, QueryFilter, QueryOrder,
131        QuerySelect,
132    };
133    pub use serde::{Deserialize, Serialize};
134    pub use serde_json::{json, Value};
135    pub use validator::Validate;
136}
137
138/// 框架版本
139pub const VERSION: &str = env!("CARGO_PKG_VERSION");
140
141/// 初始化日志
142pub fn init_logger() {
143    use tracing_subscriber::{fmt, prelude::*, EnvFilter};
144
145    tracing_subscriber::registry()
146        .with(fmt::layer())
147        .with(EnvFilter::from_default_env().add_directive("cool_core=info".parse().unwrap()))
148        .init();
149}
150
151/// 应用构建器
152pub struct CoolApp {
153    /// 配置
154    pub config: config::CoolConfig,
155    /// 数据库连接
156    pub db: Option<sea_orm::DatabaseConnection>,
157    /// 模块注册表
158    pub modules: module::ModuleRegistry,
159    /// 事件管理器
160    pub events: event::EventManager,
161}
162
163impl CoolApp {
164    /// 创建新的应用
165    pub fn new(config: config::CoolConfig) -> Self {
166        Self {
167            config,
168            db: None,
169            modules: module::ModuleRegistry::new(),
170            events: event::EventManager::new(),
171        }
172    }
173
174    /// 设置数据库连接
175    pub fn database(mut self, db: sea_orm::DatabaseConnection) -> Self {
176        self.db = Some(db);
177        self
178    }
179
180    /// 注册模块
181    pub fn register<M: module::Module + 'static>(self, module: M) -> Self {
182        self.modules.register(module);
183        self
184    }
185
186    /// 构建路由
187    pub fn build_router(&self, prefix: &str) -> salvo::Router {
188        self.modules.build_router(prefix)
189    }
190
191    /// 启动服务
192    pub async fn run(self, addr: impl Into<String>) -> std::io::Result<()> {
193        use salvo::prelude::*;
194        let addr = addr.into();
195        // 初始化所有模块
196        if let Err(e) = self.modules.init_all() {
197            tracing::error!("模块初始化失败: {}", e);
198            return Err(std::io::Error::other(e));
199        }
200
201        // 构建路由
202        let router = self.build_router("/");
203        let doc = OpenApi::new("openapi", "0.0.1").merge_router(&router);
204        let router = router
205            .unshift(doc.into_router("/api-doc/openapi.json"))
206            .unshift(SwaggerUi::new("/api-doc/openapi.json").into_router("/swagger-ui"));
207        // 解析地址
208        let listener = TcpListener::new(addr.clone()).bind().await;
209
210        tracing::info!("🚀 服务已启动: http://{}", addr);
211
212        // 触发服务就绪事件
213        self.events
214            .emit(
215                event::events::SERVER_READY,
216                event::ServerReadyEvent {
217                    address: addr.to_string(),
218                    port: 0,
219                },
220            )
221            .await;
222
223        // 启动服务
224        Server::new(listener).serve(router).await;
225
226        Ok(())
227    }
228}
229
230impl Default for CoolApp {
231    fn default() -> Self {
232        Self::new(config::CoolConfig::default())
233    }
234}