actix_web_utils/dtos/
message.rs

1use std::fmt::Display;
2
3use serde::{Serialize, Deserialize};
4
5//TODO: Add examples
6/// This is for sending errors back from requests conveniently.
7/// This struct contains an optional key just in 
8/// case you want to deal with internationalization.
9/// It was left as optional just in case you don't
10/// have the time to yet...
11#[derive(Serialize, Deserialize, Debug, Clone)]
12pub struct MessageResource{
13    pub key: Option<String>,
14    pub message: String
15}
16impl Display for MessageResource {
17    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
18        write!(f, "MessageResource Key: {:?}, Message: {}", self.key, self.message)
19    }
20}
21
22impl MessageResource{
23    pub fn new_empty() -> MessageResource{
24        MessageResource { key: None, message: String::from("") }
25    }
26    pub fn new_from_str(msg: &str) -> MessageResource{
27        MessageResource { key: None, message: String::from(msg) }
28    }
29    /// Just takes any error that implements display (Has a .to_string() method)
30    pub fn new_from_err<E: Display>(error: E) -> MessageResource{
31        MessageResource { key: None, message: error.to_string() }
32    }
33    pub fn new(key: &str, msg: &str) -> MessageResource{
34        MessageResource { key: Some(String::from(key)), message: String::from(msg) }
35    }
36}