diff --git a/api/src/controller/game_account.rs b/api/src/controller/game_account.rs index f338e47..9b3568f 100644 --- a/api/src/controller/game_account.rs +++ b/api/src/controller/game_account.rs @@ -1,16 +1,14 @@ use axum::Json; -use validator::Validate; use domain::models::game_account::GameAccountCreate; use library::resp::response::{ResErr, ResOK, ResResult}; +use validator::Validate; -pub async fn create( - Json(req): Json -) -> ResResult> { +pub async fn create(Json(req): Json) -> ResResult> { if let Err(err) = req.validate() { - return Err(ResErr::ErrParams(Some(err.to_string()))) + return Err(ResErr::ErrParams(Some(err.to_string()))); } service::game_account::create(req).await?; Ok(ResOK(None)) -} \ No newline at end of file +} diff --git a/api/src/lib.rs b/api/src/lib.rs index cb61216..c8eb16b 100644 --- a/api/src/lib.rs +++ b/api/src/lib.rs @@ -1,16 +1,14 @@ use library::config; -mod router; mod controller; +mod router; pub async fn serve() { let addr = format!("0.0.0.0:{}", config!().server.port); - let listener = tokio::net::TcpListener::bind(&addr) - .await - .unwrap(); + let listener = tokio::net::TcpListener::bind(&addr).await.unwrap(); tracing::info!("server listening {}", addr); axum::serve(listener, router::init()).await.unwrap(); -} \ No newline at end of file +} diff --git a/api/src/router.rs b/api/src/router.rs index 82ae09f..0a52ef1 100644 --- a/api/src/router.rs +++ b/api/src/router.rs @@ -1,15 +1,14 @@ +use crate::controller; use axum::body::Body; use axum::http::Request; -use axum::Router; use axum::routing::{get, post}; +use axum::Router; use tower_http::trace::TraceLayer; -use crate::controller; pub(crate) fn init() -> Router { let open = Router::new().route("/", get(|| async { "hello" })); - let auth = Router::new() - .route("/game_accounts", post(controller::game_account::create)); + let auth = Router::new().route("/game_accounts", post(controller::game_account::create)); Router::new() .nest("/", open) diff --git a/domain/src/entities/account.rs b/domain/src/entities/account.rs index e61dca9..49c387d 100644 --- a/domain/src/entities/account.rs +++ b/domain/src/entities/account.rs @@ -1,11 +1,25 @@ //! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.14 +use sea_orm::entity::prelude::*; +#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)] +#[sea_orm(table_name = "account")] +pub struct Model { + #[sea_orm(primary_key)] + pub id: u64, + #[sea_orm(unique)] + pub username: String, + pub password: String, + pub salt: String, + pub role: i8, + pub realname: String, + pub login_at: i64, + pub login_token: String, + pub created_at: i64, + pub updated_at: i64, +} -use sea_orm :: entity :: prelude :: * ; +#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] +pub enum Relation {} -# [derive (Clone , Debug , PartialEq , DeriveEntityModel , Eq)] # [sea_orm (table_name = "account")] pub struct Model { # [sea_orm (primary_key)] pub id : u64 , # [sea_orm (unique)] pub username : String , pub password : String , pub salt : String , pub role : i8 , pub realname : String , pub login_at : i64 , pub login_token : String , pub created_at : i64 , pub updated_at : i64 , } - -# [derive (Copy , Clone , Debug , EnumIter , DeriveRelation)] pub enum Relation { } - -impl ActiveModelBehavior for ActiveModel { } \ No newline at end of file +impl ActiveModelBehavior for ActiveModel {} diff --git a/domain/src/entities/game_account.rs b/domain/src/entities/game_account.rs index d926c60..7984e1c 100644 --- a/domain/src/entities/game_account.rs +++ b/domain/src/entities/game_account.rs @@ -1,11 +1,22 @@ //! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.14 +use sea_orm::entity::prelude::*; +#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)] +#[sea_orm(table_name = "game_account")] +pub struct Model { + #[sea_orm(primary_key)] + pub id: u64, + pub username: String, + pub email: Option, + #[sea_orm(unique)] + pub platform_id: String, + pub user_type: String, + pub country_code: String, + pub created_at: DateTime, +} -use sea_orm :: entity :: prelude :: * ; +#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] +pub enum Relation {} -# [derive (Clone , Debug , PartialEq , DeriveEntityModel , Eq)] # [sea_orm (table_name = "game_account")] pub struct Model { # [sea_orm (primary_key)] pub id : u64 , pub username : String , pub email : Option < String > , # [sea_orm (unique)] pub platform_id : String , pub user_type : String , pub country_code : String , pub created_at : DateTime , } - -# [derive (Copy , Clone , Debug , EnumIter , DeriveRelation)] pub enum Relation { } - -impl ActiveModelBehavior for ActiveModel { } \ No newline at end of file +impl ActiveModelBehavior for ActiveModel {} diff --git a/domain/src/entities/mod.rs b/domain/src/entities/mod.rs index e3f97fc..6ca4aeb 100644 --- a/domain/src/entities/mod.rs +++ b/domain/src/entities/mod.rs @@ -1,6 +1,5 @@ //! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.14 -pub mod prelude ; - -pub mod account ; -pub mod game_account ; \ No newline at end of file +pub mod prelude; +pub mod account; +pub mod game_account; diff --git a/domain/src/entities/prelude.rs b/domain/src/entities/prelude.rs index 34e6ca6..3159e65 100644 --- a/domain/src/entities/prelude.rs +++ b/domain/src/entities/prelude.rs @@ -1,4 +1,4 @@ //! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.14 -pub use super :: account :: Entity as Account ; -pub use super :: game_account :: Entity as GameAccount ; \ No newline at end of file +pub use super::account::Entity as Account; +pub use super::game_account::Entity as GameAccount; diff --git a/domain/src/models/game_account.rs b/domain/src/models/game_account.rs index f054fd8..4f9018a 100644 --- a/domain/src/models/game_account.rs +++ b/domain/src/models/game_account.rs @@ -12,5 +12,5 @@ pub struct GameAccountCreate { #[validate(length(min = 1, message = "用户类型不能为空"))] pub user_type: String, #[validate(length(min = 1, message = "用户所属区域不能为空"))] - pub country_code: String -} \ No newline at end of file + pub country_code: String, +} diff --git a/library/src/core/config.rs b/library/src/core/config.rs index 86c7240..0b36a4f 100644 --- a/library/src/core/config.rs +++ b/library/src/core/config.rs @@ -1,13 +1,13 @@ +use serde::Deserialize; use std::fs::File; use std::io::Read; use std::sync::OnceLock; -use serde::Deserialize; #[derive(Clone, Debug, Deserialize)] pub struct Config { pub server: Server, pub logger: Logger, - pub database: Database + pub database: Database, } #[derive(Clone, Debug, Deserialize)] @@ -19,7 +19,7 @@ pub struct Server { #[derive(Clone, Debug, Deserialize)] pub struct Database { pub url: String, - pub options: Options + pub options: Options, } #[derive(Clone, Debug, Deserialize)] @@ -29,7 +29,7 @@ pub struct Options { pub conn_timeout: u64, pub idle_timeout: u64, pub max_lifetime: u64, - pub sql_logging: bool + pub sql_logging: bool, } #[derive(Clone, Debug, Deserialize)] @@ -54,12 +54,12 @@ impl Default for Config { fn default() -> Self { let mut file = match File::open(CFG_FILE) { Ok(f) => f, - Err(err) => panic!("读取配置文件失败:{}", err) + Err(err) => panic!("读取配置文件失败:{}", err), }; let mut config_str = String::new(); match file.read_to_string(&mut config_str) { Ok(s) => s, - Err(err) => panic!("读取配置文件内容失败:{}", err) + Err(err) => panic!("读取配置文件内容失败:{}", err), }; toml::from_str(&*config_str).expect("格式化配置数据失败") } diff --git a/library/src/core/db.rs b/library/src/core/db.rs index 626c994..472aa8b 100644 --- a/library/src/core/db.rs +++ b/library/src/core/db.rs @@ -1,7 +1,7 @@ +use crate::core::config::Config; +use sea_orm::{ConnectOptions, Database, DatabaseConnection}; use std::sync::OnceLock; use std::time::Duration; -use sea_orm::{ConnectOptions, Database, DatabaseConnection}; -use crate::core::config::Config; static DB: OnceLock = OnceLock::new(); @@ -9,7 +9,8 @@ pub async fn init_database(config: &Config) { let db_cfg = &config.database; let mut conn_option = ConnectOptions::new(&db_cfg.url); - conn_option.min_connections(db_cfg.options.min_conns) + conn_option + .min_connections(db_cfg.options.min_conns) .max_connections(db_cfg.options.max_conns) .connect_timeout(Duration::from_secs(db_cfg.options.conn_timeout)) .idle_timeout(Duration::from_secs(db_cfg.options.idle_timeout)) @@ -37,4 +38,4 @@ macro_rules! db { () => { library::core::db::conn() }; -} \ No newline at end of file +} diff --git a/library/src/core/logger.rs b/library/src/core/logger.rs index fc094f8..72da731 100644 --- a/library/src/core/logger.rs +++ b/library/src/core/logger.rs @@ -1,3 +1,4 @@ +use crate::core::config::Config; use chrono::Local; use tracing::Level; use tracing_appender::non_blocking::WorkerGuard; @@ -7,7 +8,6 @@ use tracing_subscriber::fmt::time::FormatTime; use tracing_subscriber::fmt::writer::MakeWriterExt; use tracing_subscriber::layer::SubscriberExt; use tracing_subscriber::util::SubscriberInitExt; -use crate::core::config::Config; // 格式化日志的输出时间格式 struct LocalTimer; @@ -21,7 +21,9 @@ impl FormatTime for LocalTimer { pub fn init_log(config: &Config) -> (WorkerGuard, WorkerGuard) { let logger_cfg = config.logger.clone(); let (stdout_tracing_appender, std_guard) = tracing_appender::non_blocking(std::io::stdout()); - let (file_tracing_appender, file_guard) = tracing_appender::non_blocking(tracing_appender::rolling::daily(logger_cfg.dir, logger_cfg.prefix)); + let (file_tracing_appender, file_guard) = tracing_appender::non_blocking( + tracing_appender::rolling::daily(logger_cfg.dir, logger_cfg.prefix), + ); // 初始化并设置日志格式(定制和筛选日志) tracing_subscriber::registry() @@ -29,17 +31,19 @@ pub fn init_log(config: &Config) -> (WorkerGuard, WorkerGuard) { fmt::layer() .with_writer(file_tracing_appender.with_max_level(package_level(&logger_cfg.level))) .with_ansi(true) // 关掉ansi的颜色输出功能 - .with_timer(LocalTimer) + .with_timer(LocalTimer), ) .with( fmt::layer() - .with_writer(stdout_tracing_appender.with_max_level(package_level(&logger_cfg.level))) + .with_writer( + stdout_tracing_appender.with_max_level(package_level(&logger_cfg.level)), + ) // .with_file(true) .with_line_number(true) // 写入标准输出 .with_ansi(false) // 关掉ansi的颜色输出功能 .with_timer(LocalTimer) .json() - .flatten_event(true) + .flatten_event(true), ) .init(); // 初始化并将SubScriber设置为全局SubScriber @@ -55,4 +59,4 @@ fn package_level(level: &String) -> Level { "ERROR" => Level::ERROR, _ => Level::INFO, } -} \ No newline at end of file +} diff --git a/library/src/middleware/cors.rs b/library/src/middleware/cors.rs index 71366b8..8976b2f 100644 --- a/library/src/middleware/cors.rs +++ b/library/src/middleware/cors.rs @@ -1,10 +1,12 @@ use axum::{ extract::Request, + http::header::{ + ACCESS_CONTROL_ALLOW_CREDENTIALS, ACCESS_CONTROL_ALLOW_HEADERS, + ACCESS_CONTROL_ALLOW_METHODS, ACCESS_CONTROL_ALLOW_ORIGIN, + }, http::{HeaderMap, HeaderValue, Method, StatusCode}, middleware::Next, response::{IntoResponse, Response}, - http::header::{ACCESS_CONTROL_ALLOW_ORIGIN, ACCESS_CONTROL_ALLOW_CREDENTIALS, - ACCESS_CONTROL_ALLOW_HEADERS, ACCESS_CONTROL_ALLOW_METHODS}, }; pub async fn handle(request: Request, next: Next) -> Response { diff --git a/library/src/middleware/req_id.rs b/library/src/middleware/req_id.rs index db7a2e4..43a660c 100644 --- a/library/src/middleware/req_id.rs +++ b/library/src/middleware/req_id.rs @@ -10,13 +10,15 @@ pub async fn handle(mut request: Request, next: Next) -> Response { HeaderValue::from_static("unknown") }); - request.headers_mut() + request + .headers_mut() .insert(HeaderName::from_static("x-request-id"), req_id.to_owned()); let mut response = next.run(request).await; - response.headers_mut() + response + .headers_mut() .insert(HeaderName::from_static("x-request-id"), req_id); response -} \ No newline at end of file +} diff --git a/library/src/middleware/req_log.rs b/library/src/middleware/req_log.rs index dc27ba8..8e8c5eb 100644 --- a/library/src/middleware/req_log.rs +++ b/library/src/middleware/req_log.rs @@ -1,12 +1,12 @@ -use std::collections::HashMap; +use crate::resp::response::ResErr; use axum::body::Body; use axum::extract::Request; use axum::http::header::CONTENT_TYPE; use axum::http::HeaderMap; use axum::middleware::Next; use axum::response::{IntoResponse, Response}; -use crate::resp::response::ResErr; use http_body_util::BodyExt; +use std::collections::HashMap; pub async fn handle(request: Request, next: Next) -> Response { let enter_time = chrono::Local::now(); diff --git a/service/src/game_account.rs b/service/src/game_account.rs index a26577d..e85df49 100644 --- a/service/src/game_account.rs +++ b/service/src/game_account.rs @@ -1,16 +1,17 @@ -use sea_orm::{ColumnTrait, EntityTrait, PaginatorTrait, QueryFilter, Set}; use domain::entities::game_account; use domain::entities::prelude::GameAccount; use domain::models::game_account::GameAccountCreate; use library::db; use library::resp::response::ResErr::{ErrPerm, ErrSystem}; use library::resp::response::{ResOK, ResResult}; +use sea_orm::{ColumnTrait, EntityTrait, PaginatorTrait, QueryFilter, Set}; pub async fn create(req: GameAccountCreate) -> ResResult> { match GameAccount::find() .filter(game_account::Column::PlatformId.eq(req.platform_id.clone())) .count(db!()) - .await { + .await + { Err(err) => { tracing::error!(error = ?err, "err find game account"); return Err(ErrSystem(None)); @@ -40,4 +41,4 @@ pub async fn create(req: GameAccountCreate) -> ResResult> { } Ok(ResOK(None)) -} \ No newline at end of file +}