pjson_rs/application/dto/
priority_dto.rs1use crate::domain::value_objects::Priority;
7use crate::domain::{DomainError, DomainResult};
8use serde::{Deserialize, Serialize};
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
12#[serde(transparent)]
13pub struct PriorityDto {
14 value: u8,
15}
16
17impl PriorityDto {
18 pub fn new(value: u8) -> DomainResult<Self> {
20 Priority::new(value)?;
22 Ok(Self { value })
23 }
24
25 pub fn value(self) -> u8 {
27 self.value
28 }
29}
30
31impl From<Priority> for PriorityDto {
32 fn from(priority: Priority) -> Self {
33 Self {
34 value: priority.value(),
35 }
36 }
37}
38
39impl TryFrom<PriorityDto> for Priority {
40 type Error = DomainError;
41
42 fn try_from(dto: PriorityDto) -> Result<Self, Self::Error> {
43 Priority::new(dto.value)
44 }
45}
46
47pub trait ToDto<T> {
49 fn to_dto(self) -> T;
50}
51
52impl ToDto<PriorityDto> for Priority {
53 fn to_dto(self) -> PriorityDto {
54 PriorityDto::from(self)
55 }
56}
57
58pub trait FromDto<T> {
60 type Error;
61 fn from_dto(dto: T) -> Result<Self, Self::Error>
62 where
63 Self: Sized;
64}
65
66impl FromDto<PriorityDto> for Priority {
67 type Error = DomainError;
68
69 fn from_dto(dto: PriorityDto) -> Result<Self, Self::Error> {
70 Priority::try_from(dto)
71 }
72}
73
74#[cfg(test)]
75mod tests {
76 use super::*;
77 use serde_json;
78
79 #[test]
80 fn test_priority_dto_serialization() {
81 let priority = Priority::CRITICAL;
82 let dto = PriorityDto::from(priority);
83
84 let json = serde_json::to_string(&dto).unwrap();
86 assert_eq!(json, "100");
87
88 let deserialized: PriorityDto = serde_json::from_str(&json).unwrap();
90 assert_eq!(deserialized.value(), 100);
91
92 let domain_priority = Priority::from_dto(deserialized).unwrap();
94 assert_eq!(domain_priority, Priority::CRITICAL);
95 }
96
97 #[test]
98 fn test_priority_dto_validation() {
99 assert!(PriorityDto::new(100).is_ok());
101
102 assert!(PriorityDto::new(0).is_err());
104 }
105
106 #[test]
107 fn test_conversion_traits() {
108 let priority = Priority::HIGH;
109
110 let dto = priority.to_dto();
112 assert_eq!(dto.value(), 80);
113
114 let converted = Priority::from_dto(dto).unwrap();
116 assert_eq!(converted, Priority::HIGH);
117 }
118}