格式化代碼

This commit is contained in:
李运家 2024-03-10 11:11:53 +08:00
parent 4cf8b7eb08
commit aa1b3d2009
15 changed files with 90 additions and 61 deletions

View File

@ -1,16 +1,14 @@
use axum::Json; use axum::Json;
use validator::Validate;
use domain::models::game_account::GameAccountCreate; use domain::models::game_account::GameAccountCreate;
use library::resp::response::{ResErr, ResOK, ResResult}; use library::resp::response::{ResErr, ResOK, ResResult};
use validator::Validate;
pub async fn create( pub async fn create(Json(req): Json<GameAccountCreate>) -> ResResult<ResOK<()>> {
Json(req): Json<GameAccountCreate>
) -> ResResult<ResOK<()>> {
if let Err(err) = req.validate() { 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?; service::game_account::create(req).await?;
Ok(ResOK(None)) Ok(ResOK(None))
} }

View File

@ -1,16 +1,14 @@
use library::config; use library::config;
mod router;
mod controller; mod controller;
mod router;
pub async fn serve() { pub async fn serve() {
let addr = format!("0.0.0.0:{}", config!().server.port); let addr = format!("0.0.0.0:{}", config!().server.port);
let listener = tokio::net::TcpListener::bind(&addr) let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
.await
.unwrap();
tracing::info!("server listening {}", addr); tracing::info!("server listening {}", addr);
axum::serve(listener, router::init()).await.unwrap(); axum::serve(listener, router::init()).await.unwrap();
} }

View File

@ -1,15 +1,14 @@
use crate::controller;
use axum::body::Body; use axum::body::Body;
use axum::http::Request; use axum::http::Request;
use axum::Router;
use axum::routing::{get, post}; use axum::routing::{get, post};
use axum::Router;
use tower_http::trace::TraceLayer; use tower_http::trace::TraceLayer;
use crate::controller;
pub(crate) fn init() -> Router { pub(crate) fn init() -> Router {
let open = Router::new().route("/", get(|| async { "hello" })); let open = Router::new().route("/", get(|| async { "hello" }));
let auth = Router::new() let auth = Router::new().route("/game_accounts", post(controller::game_account::create));
.route("/game_accounts", post(controller::game_account::create));
Router::new() Router::new()
.nest("/", open) .nest("/", open)

View File

@ -1,11 +1,25 @@
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.14 //! `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 , } impl ActiveModelBehavior for ActiveModel {}
# [derive (Copy , Clone , Debug , EnumIter , DeriveRelation)] pub enum Relation { }
impl ActiveModelBehavior for ActiveModel { }

View File

@ -1,11 +1,22 @@
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.14 //! `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<String>,
#[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 , } impl ActiveModelBehavior for ActiveModel {}
# [derive (Copy , Clone , Debug , EnumIter , DeriveRelation)] pub enum Relation { }
impl ActiveModelBehavior for ActiveModel { }

View File

@ -1,6 +1,5 @@
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.14 //! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.14
pub mod prelude ; pub mod prelude;
pub mod account;
pub mod account ; pub mod game_account;
pub mod game_account ;

View File

@ -1,4 +1,4 @@
//! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.14 //! `SeaORM` Entity. Generated by sea-orm-codegen 0.12.14
pub use super :: account :: Entity as Account ; pub use super::account::Entity as Account;
pub use super :: game_account :: Entity as GameAccount ; pub use super::game_account::Entity as GameAccount;

View File

@ -12,5 +12,5 @@ pub struct GameAccountCreate {
#[validate(length(min = 1, message = "用户类型不能为空"))] #[validate(length(min = 1, message = "用户类型不能为空"))]
pub user_type: String, pub user_type: String,
#[validate(length(min = 1, message = "用户所属区域不能为空"))] #[validate(length(min = 1, message = "用户所属区域不能为空"))]
pub country_code: String pub country_code: String,
} }

View File

@ -1,13 +1,13 @@
use serde::Deserialize;
use std::fs::File; use std::fs::File;
use std::io::Read; use std::io::Read;
use std::sync::OnceLock; use std::sync::OnceLock;
use serde::Deserialize;
#[derive(Clone, Debug, Deserialize)] #[derive(Clone, Debug, Deserialize)]
pub struct Config { pub struct Config {
pub server: Server, pub server: Server,
pub logger: Logger, pub logger: Logger,
pub database: Database pub database: Database,
} }
#[derive(Clone, Debug, Deserialize)] #[derive(Clone, Debug, Deserialize)]
@ -19,7 +19,7 @@ pub struct Server {
#[derive(Clone, Debug, Deserialize)] #[derive(Clone, Debug, Deserialize)]
pub struct Database { pub struct Database {
pub url: String, pub url: String,
pub options: Options pub options: Options,
} }
#[derive(Clone, Debug, Deserialize)] #[derive(Clone, Debug, Deserialize)]
@ -29,7 +29,7 @@ pub struct Options {
pub conn_timeout: u64, pub conn_timeout: u64,
pub idle_timeout: u64, pub idle_timeout: u64,
pub max_lifetime: u64, pub max_lifetime: u64,
pub sql_logging: bool pub sql_logging: bool,
} }
#[derive(Clone, Debug, Deserialize)] #[derive(Clone, Debug, Deserialize)]
@ -54,12 +54,12 @@ impl Default for Config {
fn default() -> Self { fn default() -> Self {
let mut file = match File::open(CFG_FILE) { let mut file = match File::open(CFG_FILE) {
Ok(f) => f, Ok(f) => f,
Err(err) => panic!("读取配置文件失败:{}", err) Err(err) => panic!("读取配置文件失败:{}", err),
}; };
let mut config_str = String::new(); let mut config_str = String::new();
match file.read_to_string(&mut config_str) { match file.read_to_string(&mut config_str) {
Ok(s) => s, Ok(s) => s,
Err(err) => panic!("读取配置文件内容失败:{}", err) Err(err) => panic!("读取配置文件内容失败:{}", err),
}; };
toml::from_str(&*config_str).expect("格式化配置数据失败") toml::from_str(&*config_str).expect("格式化配置数据失败")
} }

View File

@ -1,7 +1,7 @@
use crate::core::config::Config;
use sea_orm::{ConnectOptions, Database, DatabaseConnection};
use std::sync::OnceLock; use std::sync::OnceLock;
use std::time::Duration; use std::time::Duration;
use sea_orm::{ConnectOptions, Database, DatabaseConnection};
use crate::core::config::Config;
static DB: OnceLock<DatabaseConnection> = OnceLock::new(); static DB: OnceLock<DatabaseConnection> = OnceLock::new();
@ -9,7 +9,8 @@ pub async fn init_database(config: &Config) {
let db_cfg = &config.database; let db_cfg = &config.database;
let mut conn_option = ConnectOptions::new(&db_cfg.url); 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) .max_connections(db_cfg.options.max_conns)
.connect_timeout(Duration::from_secs(db_cfg.options.conn_timeout)) .connect_timeout(Duration::from_secs(db_cfg.options.conn_timeout))
.idle_timeout(Duration::from_secs(db_cfg.options.idle_timeout)) .idle_timeout(Duration::from_secs(db_cfg.options.idle_timeout))
@ -37,4 +38,4 @@ macro_rules! db {
() => { () => {
library::core::db::conn() library::core::db::conn()
}; };
} }

View File

@ -1,3 +1,4 @@
use crate::core::config::Config;
use chrono::Local; use chrono::Local;
use tracing::Level; use tracing::Level;
use tracing_appender::non_blocking::WorkerGuard; 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::fmt::writer::MakeWriterExt;
use tracing_subscriber::layer::SubscriberExt; use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt; use tracing_subscriber::util::SubscriberInitExt;
use crate::core::config::Config;
// 格式化日志的输出时间格式 // 格式化日志的输出时间格式
struct LocalTimer; struct LocalTimer;
@ -21,7 +21,9 @@ impl FormatTime for LocalTimer {
pub fn init_log(config: &Config) -> (WorkerGuard, WorkerGuard) { pub fn init_log(config: &Config) -> (WorkerGuard, WorkerGuard) {
let logger_cfg = config.logger.clone(); let logger_cfg = config.logger.clone();
let (stdout_tracing_appender, std_guard) = tracing_appender::non_blocking(std::io::stdout()); 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() tracing_subscriber::registry()
@ -29,17 +31,19 @@ pub fn init_log(config: &Config) -> (WorkerGuard, WorkerGuard) {
fmt::layer() fmt::layer()
.with_writer(file_tracing_appender.with_max_level(package_level(&logger_cfg.level))) .with_writer(file_tracing_appender.with_max_level(package_level(&logger_cfg.level)))
.with_ansi(true) // 关掉ansi的颜色输出功能 .with_ansi(true) // 关掉ansi的颜色输出功能
.with_timer(LocalTimer) .with_timer(LocalTimer),
) )
.with( .with(
fmt::layer() 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_file(true)
.with_line_number(true) // 写入标准输出 .with_line_number(true) // 写入标准输出
.with_ansi(false) // 关掉ansi的颜色输出功能 .with_ansi(false) // 关掉ansi的颜色输出功能
.with_timer(LocalTimer) .with_timer(LocalTimer)
.json() .json()
.flatten_event(true) .flatten_event(true),
) )
.init(); // 初始化并将SubScriber设置为全局SubScriber .init(); // 初始化并将SubScriber设置为全局SubScriber
@ -55,4 +59,4 @@ fn package_level(level: &String) -> Level {
"ERROR" => Level::ERROR, "ERROR" => Level::ERROR,
_ => Level::INFO, _ => Level::INFO,
} }
} }

View File

@ -1,10 +1,12 @@
use axum::{ use axum::{
extract::Request, 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}, http::{HeaderMap, HeaderValue, Method, StatusCode},
middleware::Next, middleware::Next,
response::{IntoResponse, Response}, 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 { pub async fn handle(request: Request, next: Next) -> Response {

View File

@ -10,13 +10,15 @@ pub async fn handle(mut request: Request, next: Next) -> Response {
HeaderValue::from_static("unknown") HeaderValue::from_static("unknown")
}); });
request.headers_mut() request
.headers_mut()
.insert(HeaderName::from_static("x-request-id"), req_id.to_owned()); .insert(HeaderName::from_static("x-request-id"), req_id.to_owned());
let mut response = next.run(request).await; let mut response = next.run(request).await;
response.headers_mut() response
.headers_mut()
.insert(HeaderName::from_static("x-request-id"), req_id); .insert(HeaderName::from_static("x-request-id"), req_id);
response response
} }

View File

@ -1,12 +1,12 @@
use std::collections::HashMap; use crate::resp::response::ResErr;
use axum::body::Body; use axum::body::Body;
use axum::extract::Request; use axum::extract::Request;
use axum::http::header::CONTENT_TYPE; use axum::http::header::CONTENT_TYPE;
use axum::http::HeaderMap; use axum::http::HeaderMap;
use axum::middleware::Next; use axum::middleware::Next;
use axum::response::{IntoResponse, Response}; use axum::response::{IntoResponse, Response};
use crate::resp::response::ResErr;
use http_body_util::BodyExt; use http_body_util::BodyExt;
use std::collections::HashMap;
pub async fn handle(request: Request, next: Next) -> Response { pub async fn handle(request: Request, next: Next) -> Response {
let enter_time = chrono::Local::now(); let enter_time = chrono::Local::now();

View File

@ -1,16 +1,17 @@
use sea_orm::{ColumnTrait, EntityTrait, PaginatorTrait, QueryFilter, Set};
use domain::entities::game_account; use domain::entities::game_account;
use domain::entities::prelude::GameAccount; use domain::entities::prelude::GameAccount;
use domain::models::game_account::GameAccountCreate; use domain::models::game_account::GameAccountCreate;
use library::db; use library::db;
use library::resp::response::ResErr::{ErrPerm, ErrSystem}; use library::resp::response::ResErr::{ErrPerm, ErrSystem};
use library::resp::response::{ResOK, ResResult}; use library::resp::response::{ResOK, ResResult};
use sea_orm::{ColumnTrait, EntityTrait, PaginatorTrait, QueryFilter, Set};
pub async fn create(req: GameAccountCreate) -> ResResult<ResOK<()>> { pub async fn create(req: GameAccountCreate) -> ResResult<ResOK<()>> {
match GameAccount::find() match GameAccount::find()
.filter(game_account::Column::PlatformId.eq(req.platform_id.clone())) .filter(game_account::Column::PlatformId.eq(req.platform_id.clone()))
.count(db!()) .count(db!())
.await { .await
{
Err(err) => { Err(err) => {
tracing::error!(error = ?err, "err find game account"); tracing::error!(error = ?err, "err find game account");
return Err(ErrSystem(None)); return Err(ErrSystem(None));
@ -40,4 +41,4 @@ pub async fn create(req: GameAccountCreate) -> ResResult<ResOK<()>> {
} }
Ok(ResOK(None)) Ok(ResOK(None))
} }