1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
use crate::one_api::message_status::status::Status;
use crate::one_api::Channel;
use chrono::{DateTime, TimeZone, Utc};
use serde::Deserialize;
#[derive(Deserialize, PartialEq, Debug)]
pub struct Response {
sms: Option<StatusEntry>,
whatsapp: Option<StatusEntry>,
}
impl Response {
pub fn channel(&self) -> Channel {
if self.whatsapp.is_some() {
Channel::WhatsApp
} else if self.sms.is_some() {
Channel::SMS
} else {
Channel::Unknown
}
}
fn status_entry(&self) -> StatusEntry {
match self.channel() {
Channel::SMS => self.sms.unwrap_or_default(),
Channel::WhatsApp => self.whatsapp.unwrap_or_default(),
Channel::Unknown => StatusEntry::default(),
}
}
pub fn status(&self) -> Status {
self.status_entry().status
}
pub fn updated_at(&self) -> DateTime<Utc> {
Utc.timestamp_millis(self.status_entry().timestamp)
}
}
impl std::fmt::Display for Response {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{:?}", self.status())
}
}
#[derive(Deserialize, PartialEq, Debug, Clone, Copy)]
struct StatusEntry {
pub status: Status,
pub timestamp: i64,
}
impl Default for StatusEntry {
fn default() -> Self {
Self {
timestamp: Utc::now().timestamp_millis(),
status: Status::Unknown,
}
}
}
#[test]
fn test_deserialize() {
let response_200 = r#" {
"sms": {
"status": "QUEUED",
"timestamp": 1506607698000
}
}"#;
let response = serde_json::from_str::<Response>(response_200).unwrap();
assert_eq!(Channel::SMS, response.channel());
assert_eq!(Status::Queued, response.status());
}