Skip to content
This repository was archived by the owner on Mar 7, 2025. It is now read-only.

Commit fccc404

Browse files
committed
Merge branch 'simplify'
2 parents 44b0e93 + dacd0d5 commit fccc404

5 files changed

Lines changed: 26 additions & 141 deletions

File tree

Cargo.toml

Lines changed: 2 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,47 +1,22 @@
11
[package]
22
name = "cc-utils"
33
description = "Rust Fullstack utils (strict error handling, `Consider` trait, MessagePack support, etc.) for Salvo and Yew/Dioxus/Leptos/*"
4-
version = "0.4.0"
4+
version = "0.5.1"
55
edition = "2021"
66
license = "MIT"
77
authors = ["Klimenty Titov <aclo.create@gmail.com>"]
88
repository = "https://github.com/markcda/cc-utils"
99

1010
[features]
11-
default = ["salvo", "reqwest", "base64", "bb8-redis", "sea-orm", "dotenv", "serde-yaml", "tracing-appender", "uuid", "sqlx", "web-sys", "web-ws"]
12-
base64 = ["dep:base64"]
11+
default = ["salvo", "reqwest"]
1312
salvo = ["dep:salvo"]
1413
reqwest = ["dep:reqwest"]
15-
bb8-redis = ["dep:bb8", "dep:bb8-redis"]
16-
bb8-mongo = ["dep:bb8", "dep:mongodb", "dep:bb8-mongodb"]
17-
sea-orm = ["dep:sea-orm"]
18-
dotenv = ["dep:dotenv"]
19-
serde-yaml = ["dep:serde_yaml"]
20-
tracing-appender = ["dep:tracing-appender"]
21-
uuid = ["dep:uuid"]
22-
sqlx = ["dep:sqlx"]
23-
web-sys = ["dep:web-sys"]
24-
web-ws = ["dep:ws_stream_wasm"]
2514

2615
[dependencies]
2716
anyhow = "1.0"
28-
base64 = { version = "0.22", optional = true }
29-
bb8 = { version = "0.8", optional = true }
30-
bb8-mongodb = { version = "0.2", optional = true }
31-
bb8-redis = { version = "0.15", optional = true }
32-
dotenv = { version = "0.15", optional = true }
33-
log = "0.4"
34-
mongodb = { version = "2.8", optional = true }
3517
reqwest = { git = "https://github.com/markcda/reqwest.git", branch = "msgpack-support", default-features = false, features = ["json", "rustls-tls"], optional = true }
3618
rmp-serde = "1.3"
3719
salvo = { version = "0.74", features = ["oapi", "rustls"], optional = true }
38-
sea-orm = { version = "1.1", optional = true }
3920
serde = { version = "1", features = ["derive"] }
4021
serde_json = "1"
41-
serde_yaml = { version = "0.9", optional = true }
42-
sqlx = { version = "0.7", default-features = false, optional = true }
4322
tracing = "0.1"
44-
tracing-appender = { version = "0.2", optional = true }
45-
uuid = { version = "1", features = ["v4", "serde"], optional = true }
46-
web-sys = { version = "0.3", optional = true }
47-
ws_stream_wasm = { version = "0.7", optional = true }

src/errors.rs

Lines changed: 3 additions & 94 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,6 @@
44
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
55
use std::any::Any;
66

7-
#[cfg(any(target_arch = "wasm32", target_arch = "wasm64"))]
8-
use std::fmt::Write;
9-
107
#[cfg(feature = "salvo")]
118
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
129
use salvo::http::StatusCode;
@@ -257,9 +254,8 @@ impl ErrorResponse {
257254

258255
/// Changes error message text.
259256
pub fn with_text(&mut self, text: impl Into<String>) -> &mut Self {
260-
match self.original_text {
261-
None => self.original_text = Some(self.error_text.to_owned()),
262-
Some(_) => {}
257+
if self.original_text.is_none() {
258+
self.original_text = Some(self.error_text.to_owned());
263259
}
264260
self.error_text = text.into();
265261
self
@@ -570,8 +566,6 @@ impl_consider!(std::env::VarError);
570566
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
571567
impl_consider!(std::sync::mpsc::RecvError);
572568
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
573-
impl_consider!(log::SetLoggerError);
574-
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
575569
impl_consider!(serde_json::Error);
576570
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
577571
impl_consider!(BoxDynError);
@@ -668,58 +662,14 @@ impl<U> From<std::sync::mpsc::SendError<U>> for ErrorResponse {
668662
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
669663
impl_consider!(salvo::http::header::ToStrError);
670664

671-
#[cfg(feature = "bb8-redis")]
672-
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
673-
impl_consider!(bb8_redis::redis::RedisError);
674-
675-
#[cfg(feature = "bb8-redis")]
676-
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
677-
impl_consider!(bb8::RunError<bb8_redis::redis::RedisError>);
678-
679-
#[cfg(feature = "bb8-mongo")]
680-
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
681-
impl_consider!(bb8_mongodb::Error);
682-
683-
#[cfg(feature = "bb8-mongo")]
684-
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
685-
impl_consider!(mongodb::error::Error);
686-
687-
#[cfg(feature = "dotenv")]
688-
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
689-
impl_consider!(dotenv::Error);
690-
691-
#[cfg(feature = "sea-orm")]
692-
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
693-
impl_consider!(sea_orm::DbErr);
694-
695-
#[cfg(feature = "serde-yaml")]
696-
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
697-
impl_consider!(serde_yaml::Error);
698-
699665
#[cfg(feature = "reqwest")]
700666
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
701667
impl_consider!(reqwest::Error);
702668

703-
#[cfg(feature = "base64")]
704-
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
705-
impl_consider!(base64::DecodeError);
706-
707-
#[cfg(feature = "uuid")]
708-
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
709-
impl_consider!(uuid::Error);
710-
711-
#[cfg(feature = "sqlx")]
712-
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
713-
impl_consider!(sqlx::Error);
714-
715669
#[cfg(feature = "salvo")]
716670
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
717671
impl_consider!(salvo::http::errors::StatusError);
718672

719-
#[cfg(feature = "tracing-appender")]
720-
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
721-
impl_consider!(tracing_appender::rolling::InitError);
722-
723673
#[cfg(any(target_arch = "wasm32", target_arch = "wasm64"))]
724674
impl_consider_cli!(rmp_serde::encode::Error);
725675
#[cfg(any(target_arch = "wasm32", target_arch = "wasm64"))]
@@ -729,51 +679,10 @@ impl_consider_cli!(std::io::Error);
729679
#[cfg(any(target_arch = "wasm32", target_arch = "wasm64"))]
730680
impl_consider_cli!(std::string::FromUtf8Error);
731681
#[cfg(any(target_arch = "wasm32", target_arch = "wasm64"))]
732-
impl_consider_cli!(log::SetLoggerError);
733-
#[cfg(any(target_arch = "wasm32", target_arch = "wasm64"))]
734682
impl_consider_cli!(serde_json::Error);
735683
#[cfg(any(target_arch = "wasm32", target_arch = "wasm64"))]
736684
impl_consider_cli!(BoxDynError);
737685

738686
#[cfg(feature = "reqwest")]
739687
#[cfg(any(target_arch = "wasm32", target_arch = "wasm64"))]
740-
impl_consider_cli!(reqwest::Error);
741-
742-
#[cfg(feature = "base64")]
743-
#[cfg(any(target_arch = "wasm32", target_arch = "wasm64"))]
744-
impl_consider_cli!(base64::DecodeError);
745-
746-
#[cfg(feature = "uuid")]
747-
#[cfg(any(target_arch = "wasm32", target_arch = "wasm64"))]
748-
impl_consider_cli!(uuid::Error);
749-
750-
#[cfg(feature = "web-sys")]
751-
#[cfg(any(target_arch = "wasm32", target_arch = "wasm64"))]
752-
impl<T> ConsiderCli<T> for Result<T, web_sys::wasm_bindgen::JsValue> {
753-
/// Изменяет параметры возможной ошибки на указанные.
754-
fn consider_cli(self, error_text_replacement: Option<String>) -> Result<T, CliError> {
755-
self.map_err(|e| {
756-
let mut new_error = CliError {
757-
message: e.as_string().unwrap_or_default(),
758-
};
759-
if error_text_replacement.is_some() {
760-
new_error.message = error_text_replacement.unwrap();
761-
}
762-
new_error
763-
})
764-
}
765-
}
766-
767-
#[cfg(feature = "web-sys")]
768-
#[cfg(any(target_arch = "wasm32", target_arch = "wasm64"))]
769-
impl From<web_sys::wasm_bindgen::JsValue> for CliError {
770-
/// Создаёт `CliError` из данной ошибки.
771-
fn from(value: web_sys::wasm_bindgen::JsValue) -> Self {
772-
let s = value.as_string().unwrap_or_default();
773-
format!("Ошибка в JavaScript: {}", s).into()
774-
}
775-
}
776-
777-
#[cfg(feature = "web-ws")]
778-
#[cfg(any(target_arch = "wasm32", target_arch = "wasm64"))]
779-
impl_consider_cli!(ws_stream_wasm::WsErr);
688+
impl_consider_cli!(reqwest::Error);

src/prelude.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ pub use crate::errors::{CliError, ConsiderCli};
3030

3131
#[cfg(feature = "salvo")]
3232
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
33-
pub use crate::{ok, plain, html, file, json, msgpack};
33+
pub use crate::{ok, plain, html, file_upload, json, msgpack};
3434

3535
#[cfg(feature = "salvo")]
3636
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]

src/requests.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
//! Implementation of utilities for working with MessagePack with requests in `salvo` and `reqwest`.
22
3+
#[cfg(feature = "salvo")]
4+
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
35
use crate::prelude::*;
46

57
#[cfg(feature = "salvo")]
@@ -39,7 +41,7 @@ impl MsgPackParser for Request {
3941
} else {
4042
payload.as_ref()
4143
};
42-
log::debug!("{:?}", payload);
44+
tracing::debug!("{:?}", payload);
4345
return rmp_serde::from_slice::<T>(payload).consider(Some(StatusCode::BAD_REQUEST), None::<String>, true)
4446
}
4547
}

src/responses.rs

Lines changed: 17 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ impl_oapi_endpoint_out!(OK, "text/plain");
9797
#[cfg(feature = "salvo")]
9898
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
9999
#[macro_export]
100-
macro_rules! ok { () => { Ok(OK($crate::fn_name!())) }; }
100+
macro_rules! ok { () => { Ok(cc_utils::responses::OK($crate::fn_name!())) } }
101101

102102
#[cfg(feature = "salvo")]
103103
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
@@ -106,7 +106,7 @@ impl ServerResponseWriter for OK {
106106
async fn write(self, _req: &mut Request, _depot: &mut Depot, res: &mut Response) {
107107
res.status_code(StatusCode::OK);
108108
res.render("");
109-
log::debug!("[{}] => Received and sent result 200", self.0);
109+
tracing::debug!("[{}] => Received and sent result 200", self.0);
110110
}
111111
}
112112

@@ -123,7 +123,7 @@ impl_oapi_endpoint_out!(Plain, "text/plain");
123123
#[cfg(feature = "salvo")]
124124
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
125125
#[macro_export]
126-
macro_rules! plain { ($plain_text:expr) => { Ok(Plain($plain_text, $crate::fn_name!())) }; }
126+
macro_rules! plain { ($plain_text:expr) => { Ok(cc_utils::responses::Plain($plain_text, $crate::fn_name!())) } }
127127

128128
#[cfg(feature = "salvo")]
129129
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
@@ -132,7 +132,7 @@ impl ServerResponseWriter for Plain {
132132
async fn write(self, _req: &mut Request, _depot: &mut Depot, res: &mut Response) {
133133
res.status_code(StatusCode::OK);
134134
res.render(&self.0);
135-
log::debug!("[{}] => Received and sent result 200 with text: {}", self.1, self.0);
135+
tracing::debug!("[{}] => Received and sent result 200 with text: {}", self.1, self.0);
136136
}
137137
}
138138

@@ -149,7 +149,7 @@ impl_oapi_endpoint_out!(Html, "text/html");
149149
#[cfg(feature = "salvo")]
150150
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
151151
#[macro_export]
152-
macro_rules! html { ($html_data:expr) => { Ok(Html($html_data, $crate::fn_name!())) }; }
152+
macro_rules! html { ($html_data:expr) => { Ok(cc_utils::responses::Html($html_data, $crate::fn_name!())) } }
153153

154154
#[cfg(feature = "salvo")]
155155
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
@@ -158,7 +158,7 @@ impl ServerResponseWriter for Html {
158158
async fn write(self, _req: &mut Request, _depot: &mut Depot, res: &mut Response) {
159159
res.status_code(StatusCode::OK);
160160
res.render(salvo::writing::Text::Html(&self.0));
161-
log::debug!("[{}] => Received and sent result 200 with HTML", self.1);
161+
tracing::debug!("[{}] => Received and sent result 200 with HTML", self.1);
162162
}
163163
}
164164

@@ -181,13 +181,13 @@ impl_oapi_endpoint_out!(File, "application/octet-stream");
181181
/// use salvo::prelude::*;
182182
///
183183
/// pub async fn some_endpoint() -> MResult<File> {
184-
/// file!("filepath", "Normal file name")
184+
/// file_upload!("filepath".to_string(), "Normal file name".to_string())
185185
/// }
186186
/// ```
187187
#[cfg(feature = "salvo")]
188188
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
189189
#[macro_export]
190-
macro_rules! file { ($filepath:expr, $attached_filename:expr) => { Ok(File($filepath, $attached_filename, $crate::fn_name!())) }; }
190+
macro_rules! file_upload { ($filepath:expr, $attached_filename:expr) => { Ok(cc_utils::responses::File($filepath, $attached_filename, $crate::fn_name!())) } }
191191

192192
#[cfg(feature = "salvo")]
193193
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
@@ -196,7 +196,7 @@ impl ServerResponseWriter for File {
196196
async fn write(self, req: &mut Request, _depot: &mut Depot, res: &mut Response) {
197197
res.status_code(StatusCode::OK);
198198
NamedFile::builder(&self.0).attached_name(&self.1).use_last_modified(true).send(req.headers(), res).await;
199-
log::debug!("[{}] => Received and sent result 200 with file {}", self.2, self.1);
199+
tracing::debug!("[{}] => Received and sent result 200 with file {}", self.2, self.1);
200200
}
201201
}
202202

@@ -213,7 +213,7 @@ impl_oapi_endpoint_out_t!(Json, "application/json");
213213
#[cfg(feature = "salvo")]
214214
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
215215
#[macro_export]
216-
macro_rules! json { ($json_data:expr) => { Ok(Json($json_data, $crate::fn_name!())) }; }
216+
macro_rules! json { ($json_data:expr) => { Ok(cc_utils::responses::Json($json_data, $crate::fn_name!())) } }
217217

218218
#[cfg(feature = "salvo")]
219219
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
@@ -224,16 +224,15 @@ impl<T: Serialize + Send> ServerResponseWriter for Json<T> {
224224
match serde_json::to_string(&self.0) {
225225
Ok(s) => {
226226
res.headers_mut().insert(CONTENT_TYPE, HeaderValue::from_static("application/json; charset=utf-8"));
227-
log::debug!("[{}] => Sending JSON: {:?}", self.1, s.as_str());
227+
tracing::debug!("[{}] => Sending JSON: {:?}", self.1, s.as_str());
228228
res.write_body(s).ok();
229-
log::debug!("[{}] => Received and sent result 200 with JSON", self.1);
229+
tracing::debug!("[{}] => Received and sent result 200 with JSON", self.1);
230230
}
231231
Err(e) => {
232-
log::error!("[{}] => Failed to serialize data: {:?}", e, self.1);
232+
tracing::error!("[{}] => Failed to serialize data: {:?}", e, self.1);
233233
ErrorResponse::from("Failed to serialize data.").with_500().build().write(req, depot, res).await;
234234
}
235235
}
236-
log::debug!("[{}] => Received and sent result 200 with JSON", self.1);
237236
}
238237
}
239238

@@ -250,7 +249,7 @@ impl_oapi_endpoint_out_t!(MsgPack, "application/msgpack");
250249
#[cfg(feature = "salvo")]
251250
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
252251
#[macro_export]
253-
macro_rules! msgpack { ($msgpack_data:expr) => { Ok(MsgPack($msgpack_data, $crate::fn_name!())) }; }
252+
macro_rules! msgpack { ($msgpack_data:expr) => { Ok(cc_utils::responses::MsgPack($msgpack_data, $crate::fn_name!())) } }
254253

255254
#[cfg(feature = "salvo")]
256255
#[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
@@ -261,12 +260,12 @@ impl<T: Serialize + Send> ServerResponseWriter for MsgPack<T> {
261260
match rmp_serde::to_vec(&self.0) {
262261
Ok(bytes) => {
263262
res.headers_mut().insert(CONTENT_TYPE, HeaderValue::from_static("application/msgpack; charset=utf-8"));
264-
log::debug!("[{}] => Sending bytes: {:?}", self.1, bytes);
263+
tracing::debug!("[{}] => Sending bytes: {:?}", self.1, bytes);
265264
res.write_body(bytes).ok();
266-
log::debug!("[{}] => Received and sent result 200 with MsgPack", self.1);
265+
tracing::debug!("[{}] => Received and sent result 200 with MsgPack", self.1);
267266
}
268267
Err(e) => {
269-
log::error!("[{}] => Failed to serialize data: {:?}", e, self.1);
268+
tracing::error!("[{}] => Failed to serialize data: {:?}", e, self.1);
270269
ErrorResponse::from("Failed to serialize data.").with_500().build().write(req, depot, res).await;
271270
}
272271
}

0 commit comments

Comments
 (0)