Skip to content

Commit

Permalink
Update ApiResult
Browse files Browse the repository at this point in the history
  • Loading branch information
shenghui0779 committed Oct 29, 2024
1 parent 1119218 commit be9599e
Show file tree
Hide file tree
Showing 14 changed files with 180 additions and 177 deletions.
289 changes: 145 additions & 144 deletions Cargo.lock

Large diffs are not rendered by default.

7 changes: 3 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
# yiirs

Rust API 快速开发脚手架
基于 [salvo](https://github.com/salvo-rs/salvo)Rust API 快速开发脚手架

- 路由使用 [salvo](https://github.com/salvo-rs/salvo)
- ORM使用 [sea-orm](https://github.com/SeaQL/sea-orm)
- Redis使用 [redis-rs](https://github.com/redis-rs/redis-rs)
- 日志使用 [tracing](https://github.com/tokio-rs/tracing)
Expand All @@ -13,7 +12,7 @@ Rust API 快速开发脚手架
- 包含基础的登录授权功能
- 包含基于 Redis 的分布式锁
- 包含 AES、Hash、时间格式化 等实用封装
- 包含 Trace、认证、请求日志 中间价
- 包含 Trace、认证、请求日志、Panic捕获 中间价
- 简单好用的 API Result 统一输出方式

#### 1. 模块说明
Expand All @@ -31,5 +30,5 @@ demo_rs.sql
mv config.toml.example config.toml

# 启动服务
cargo run -- serve
cargo run serve
```
4 changes: 2 additions & 2 deletions src/app/api/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use salvo::{handler, Request};
use validator::Validate;

use crate::shared::{
result::{code::Code, status, ApiResult},
result::{code::Code, reply, ApiResult},
util::identity::Identity,
};

Expand All @@ -28,7 +28,7 @@ pub async fn logout(req: &mut Request) -> ApiResult<()> {
let empty = Identity::empty();
let id = req.extensions().get::<Identity>().unwrap_or(&empty);
if id.id() == 0 {
return Ok(status::OK(None));
return Ok(reply::OK(None));
}
service::auth::logout(id).await
}
2 changes: 1 addition & 1 deletion src/app/middleware/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ impl Handler for Auth {
let empty = Identity::empty();
let id = req.extensions().get::<Identity>().unwrap_or(&empty);
if let Err(e) = auth_check(id).await {
resp.render(Json(Code::ErrAuth(Some(e.to_string())).to_status()));
resp.render(Json(Code::ErrAuth(Some(e.to_string())).to_reply()));
ctrl.skip_rest();
return;
}
Expand Down
8 changes: 4 additions & 4 deletions src/app/service/account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use validator::Validate;
use crate::shared::core::db;
use crate::shared::crypto::hash;
use crate::shared::result::code::Code;
use crate::shared::result::{status, ApiResult};
use crate::shared::result::{reply, ApiResult};
use crate::shared::util::{helper, xtime};

use crate::app::model::{account, prelude::Account};
Expand Down Expand Up @@ -55,7 +55,7 @@ pub async fn create(req: ReqCreate) -> ApiResult<()> {
return Err(Code::ErrSystem(None));
}

Ok(status::OK(None))
Ok(reply::OK(None))
}

#[derive(Debug, Serialize)]
Expand Down Expand Up @@ -90,7 +90,7 @@ pub async fn info(account_id: u64) -> ApiResult<RespInfo> {
.unwrap_or_default(),
};

Ok(status::OK(Some(resp)))
Ok(reply::OK(Some(resp)))
}

#[derive(Debug, Serialize)]
Expand Down Expand Up @@ -154,5 +154,5 @@ pub async fn list(query: &MultiMap<String, String>) -> ApiResult<RespList> {
resp.list.push(info);
}

Ok(status::OK(Some(resp)))
Ok(reply::OK(Some(resp)))
}
6 changes: 3 additions & 3 deletions src/app/service/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use crate::app::model::{account, prelude::Account};
use crate::shared::core::db;
use crate::shared::crypto::hash;
use crate::shared::result::code::Code;
use crate::shared::result::{status, ApiResult};
use crate::shared::result::{reply, ApiResult};
use crate::shared::util::identity::Identity;
use crate::shared::util::{helper, xtime};

Expand Down Expand Up @@ -73,7 +73,7 @@ pub async fn login(req: ReqLogin) -> ApiResult<RespLogin> {
auth_token,
};

Ok(status::OK(Some(resp)))
Ok(reply::OK(Some(resp)))
}

pub async fn logout(identity: &Identity) -> ApiResult<()> {
Expand All @@ -92,5 +92,5 @@ pub async fn logout(identity: &Identity) -> ApiResult<()> {
return Err(Code::ErrSystem(None));
}

Ok(status::OK(None))
Ok(reply::OK(None))
}
8 changes: 4 additions & 4 deletions src/app/service/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use validator::Validate;

use crate::shared::core::db;
use crate::shared::result::code::Code;
use crate::shared::result::{status, ApiResult};
use crate::shared::result::{reply, ApiResult};
use crate::shared::util::identity::{Identity, Role};
use crate::shared::util::{helper, xtime};

Expand Down Expand Up @@ -52,7 +52,7 @@ pub async fn create(id: &Identity, req: ReqCreate) -> ApiResult<()> {
return Err(Code::ErrSystem(None));
}

Ok(status::OK(None))
Ok(reply::OK(None))
}

#[derive(Debug, Serialize)]
Expand Down Expand Up @@ -136,7 +136,7 @@ pub async fn list(id: &Identity, query: &MultiMap<String, String>) -> ApiResult<
resp.list.push(info);
}

Ok(status::OK(Some(resp)))
Ok(reply::OK(Some(resp)))
}

#[derive(Debug, Serialize)]
Expand Down Expand Up @@ -185,5 +185,5 @@ pub async fn detail(id: &Identity, project_id: u64) -> ApiResult<RespDetail> {
})
}

Ok(status::OK(Some(resp)))
Ok(reply::OK(Some(resp)))
}
2 changes: 1 addition & 1 deletion src/shared/middleware/catch_panic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ impl Handler for CatchPanic {
.catch_unwind()
.await
{
resp.render(Json(Code::ErrSystem(None).to_status()));
resp.render(Json(Code::ErrSystem(None).to_reply()));
}
}
}
2 changes: 1 addition & 1 deletion src/shared/middleware/log.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ impl Handler for Log {
// 获取body
let (body, code) = drain_body(req).await;
if let Some(v) = code {
resp.render(Json(v.to_status()));
resp.render(Json(v.to_reply()));
ctrl.skip_rest();
return;
}
Expand Down
6 changes: 3 additions & 3 deletions src/shared/middleware/trace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use tracing::Instrument;

use crate::shared::{crypto::hash, util::identity::Identity};

pub const TRACE_ID: &str = "x-trace-id";
pub const TRACE_ID: HeaderName = HeaderName::from_static("x-trace-id");

pub struct Trace;

Expand Down Expand Up @@ -54,7 +54,7 @@ impl Handler for Trace {
ctrl.call_next(req, depot, resp).instrument(span).await;
// 设置返回header
resp.headers_mut().insert(
HeaderName::from_static(TRACE_ID),
TRACE_ID,
HeaderValue::from_str(&trace_id).unwrap_or(HeaderValue::from_static("")),
);
}
Expand All @@ -63,7 +63,7 @@ impl Handler for Trace {
fn gen_trace_id(req: &mut Request, hostname: &str) -> String {
let id = hash::md5(format!("{}/{}", hostname, nanoid!(32)).as_bytes());
req.headers_mut().insert(
HeaderName::from_static(TRACE_ID),
TRACE_ID,
HeaderValue::from_str(&id).unwrap_or(HeaderValue::from_static("")),
);
id
Expand Down
8 changes: 4 additions & 4 deletions src/shared/result/code.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use salvo::prelude::*;
use salvo::{Depot, Request, Response, Writer};

use super::status::Status;
use super::reply::Reply;

pub enum Code {
New(i32, String),
Expand All @@ -15,7 +15,7 @@ pub enum Code {
}

impl Code {
pub fn to_status(self) -> Status<()> {
pub fn to_reply(self) -> Reply<()> {
let (code, msg) = match self {
Code::New(code, msg) => (code, msg),
Code::ErrParams(msg) => (10000, msg.unwrap_or(String::from("参数错误"))),
Expand All @@ -26,7 +26,7 @@ impl Code {
Code::ErrData(msg) => (60000, msg.unwrap_or(String::from("数据异常"))),
Code::ErrService(msg) => (70000, msg.unwrap_or(String::from("服务异常"))),
};
Status {
Reply {
code,
err: true,
msg,
Expand All @@ -38,6 +38,6 @@ impl Code {
#[async_trait]
impl Writer for Code {
async fn write(mut self, _req: &mut Request, _depot: &mut Depot, resp: &mut Response) {
resp.render(Json(self.to_status()));
resp.render(Json(self.to_reply()));
}
}
4 changes: 2 additions & 2 deletions src/shared/result/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
pub mod code;
pub mod status;
pub mod reply;

pub type ApiResult<T> = Result<status::OK<T>, code::Code>;
pub type ApiResult<T> = Result<reply::OK<T>, code::Code>;
8 changes: 4 additions & 4 deletions src/shared/result/status.rs → src/shared/result/reply.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use salvo::{Depot, Request, Response, Writer};
use serde::Serialize;

#[derive(Serialize)]
pub struct Status<T>
pub struct Reply<T>
where
T: Serialize,
{
Expand All @@ -22,8 +22,8 @@ impl<T> OK<T>
where
T: Serialize + std::marker::Send,
{
pub fn to_status(self) -> Status<T> {
Status {
pub fn to_reply(self) -> Reply<T> {
Reply {
code: 0,
err: false,
msg: String::from("OK"),
Expand All @@ -38,6 +38,6 @@ where
T: Serialize + std::marker::Send,
{
async fn write(mut self, _req: &mut Request, _depot: &mut Depot, resp: &mut Response) {
resp.render(Json(self.to_status()));
resp.render(Json(self.to_reply()));
}
}
3 changes: 3 additions & 0 deletions src/shared/util/identity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@ impl Identity {
}

pub fn from_auth_token(token: String) -> Self {
if token.len() == 0 {
return Identity::empty();
}
let cipher = match BASE64_STANDARD.decode(token) {
Err(e) => {
tracing::error!(error = ?e, "error invalid auth_token");
Expand Down

0 comments on commit be9599e

Please sign in to comment.