params_utils.rs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. use std::str::FromStr;
  2. use actix_web::HttpResponse;
  3. use rust_decimal::{Decimal};
  4. use serde_json::Value;
  5. use crate::server::Response;
  6. pub fn parse_str_to_decimal(value: Value, param_name: &str) -> Result<Decimal, HttpResponse> {
  7. match get_str(value.clone(), param_name) {
  8. Ok(decimal_str) => {
  9. match Decimal::from_str(decimal_str.as_str()) {
  10. Ok(rst) => {
  11. Ok(rst)
  12. }
  13. Err(_) => {
  14. // 返回数据
  15. let response = Response {
  16. query: value.clone(),
  17. msg: Some(format!("{}你传的怕不是个数字啊 你传的是: {}", param_name, value[param_name])),
  18. code: 500,
  19. data: Value::Null,
  20. };
  21. let json_string = serde_json::to_string(&response).unwrap();
  22. Err(HttpResponse::Ok().content_type("application/json").body(json_string))
  23. }
  24. }
  25. }
  26. Err(response) => {
  27. Err(response)
  28. }
  29. }
  30. }
  31. pub fn get_str(value: Value, param_name: &str) -> Result<String, HttpResponse> {
  32. match value[param_name].as_str() {
  33. None => {
  34. // 返回数据
  35. let response = Response {
  36. query: value.clone(),
  37. msg: Some(format!("{}是必填项, 你的参数: {}", param_name, value.to_string())),
  38. code: 500,
  39. data: Value::Null,
  40. };
  41. let json_string = serde_json::to_string(&response).unwrap();
  42. Err(HttpResponse::Ok().content_type("application/json").body(json_string))
  43. }
  44. Some(str) => {
  45. if str.is_empty() {
  46. // 返回数据
  47. let response = Response {
  48. query: value.clone(),
  49. msg: Some(format!("{}传了个空字符串", param_name)),
  50. code: 500,
  51. data: Value::Null,
  52. };
  53. let json_string = serde_json::to_string(&response).unwrap();
  54. Err(HttpResponse::Ok().content_type("application/json").body(json_string))
  55. } else {
  56. Ok(str.to_string())
  57. }
  58. }
  59. }
  60. }
  61. #[tokio::test]
  62. async fn test_decimal_to_i64() {
  63. use global::log_utils::init_log_with_info;
  64. use tracing::info;
  65. use rust_decimal_macros::dec;
  66. use rust_decimal::prelude::ToPrimitive;
  67. init_log_with_info();
  68. info!("{}", dec!(50).to_i64().unwrap());
  69. info!("{}", dec!(50.5).to_i64().unwrap());
  70. }