格式化代碼

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 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<GameAccountCreate>
) -> ResResult<ResOK<()>> {
pub async fn create(Json(req): Json<GameAccountCreate>) -> ResResult<ResOK<()>> {
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))
}
}

View File

@ -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();
}
}

View File

@ -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)

View File

@ -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 { }
impl ActiveModelBehavior for ActiveModel {}

View File

@ -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<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 , }
# [derive (Copy , Clone , Debug , EnumIter , DeriveRelation)] pub enum Relation { }
impl ActiveModelBehavior for ActiveModel { }
impl ActiveModelBehavior for ActiveModel {}

View File

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

View File

@ -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 ;
pub use super::account::Entity as Account;
pub use super::game_account::Entity as GameAccount;

View File

@ -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
}
pub country_code: String,
}

View File

@ -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("格式化配置数据失败")
}

View File

@ -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<DatabaseConnection> = 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()
};
}
}

View File

@ -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,
}
}
}

View File

@ -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 {

View File

@ -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
}
}

View File

@ -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();

View File

@ -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<ResOK<()>> {
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<ResOK<()>> {
}
Ok(ResOK(None))
}
}