@@ -9,28 +9,14 @@ pub struct NotificationCookie {
9
9
pub time_modal_viewed : Option < chrono:: DateTime < chrono:: Utc > > ,
10
10
}
11
11
12
- impl std:: fmt:: Display for NotificationCookie {
13
- fn fmt ( & self , f : & mut std:: fmt:: Formatter < ' _ > ) -> std:: fmt:: Result {
14
- let mut rsp = format ! ( r#"{{"id": "{}""# , self . id. clone( ) ) ;
15
- if self . time_viewed . is_some ( ) {
16
- rsp. push_str ( & format ! ( r#", "time_viewed": "{}""# , self . time_viewed. clone( ) . unwrap( ) ) ) ;
17
- }
18
- if self . time_modal_viewed . is_some ( ) {
19
- rsp. push_str ( & format ! (
20
- r#", "time_modal_viewed": "{}""# ,
21
- self . time_modal_viewed. clone( ) . unwrap( )
22
- ) ) ;
23
- }
24
- rsp. push_str ( "}" ) ;
25
- return write ! ( f, "{}" , rsp) ;
26
- }
27
- }
28
-
29
12
pub struct Notifications { }
30
13
31
14
impl Notifications {
32
15
pub fn update_viewed ( new : & Vec < NotificationCookie > , cookies : & CookieJar < ' _ > ) {
33
- let serialized = new. iter ( ) . map ( |x| x. to_string ( ) ) . collect :: < Vec < String > > ( ) ;
16
+ let serialized = new
17
+ . iter ( )
18
+ . map ( |x| serde_json:: to_string ( x) . unwrap ( ) )
19
+ . collect :: < Vec < String > > ( ) ;
34
20
35
21
let mut cookie = Cookie :: new ( "session" , format ! ( r#"{{"notifications": [{}]}}"# , serialized. join( "," ) ) ) ;
36
22
cookie. set_max_age ( :: time:: Duration :: weeks ( 4 ) ) ;
@@ -40,10 +26,30 @@ impl Notifications {
40
26
pub fn get_viewed ( cookies : & CookieJar < ' _ > ) -> Vec < NotificationCookie > {
41
27
let viewed: Vec < NotificationCookie > = match cookies. get_private ( "session" ) {
42
28
Some ( session) => {
43
- match serde_json:: from_str :: < serde_json:: Value > ( session. value ( ) ) . unwrap ( ) [ "notifications" ] . as_array ( ) {
29
+ match serde_json:: from_str :: < serde_json:: Value > ( session. value ( ) )
30
+ . unwrap_or_else ( |_| serde_json:: from_str :: < serde_json:: Value > ( r#"{"notifications": []}"# ) . unwrap ( ) )
31
+ [ "notifications" ]
32
+ . as_array ( )
33
+ {
44
34
Some ( items) => items
45
35
. into_iter ( )
46
- . map ( |x| serde_json:: from_str :: < NotificationCookie > ( & x. to_string ( ) ) . unwrap ( ) )
36
+ . map ( |x| {
37
+ serde_json:: from_str :: < NotificationCookie > ( & x. to_string ( ) ) . unwrap_or_else ( |_| {
38
+ serde_json:: from_str :: < String > ( & x. to_string ( ) )
39
+ . and_then ( |z| {
40
+ Ok ( NotificationCookie {
41
+ id : z,
42
+ time_viewed : None ,
43
+ time_modal_viewed : None ,
44
+ } )
45
+ } )
46
+ . unwrap_or_else ( |_| NotificationCookie {
47
+ id : "" . to_string ( ) ,
48
+ time_viewed : None ,
49
+ time_modal_viewed : None ,
50
+ } )
51
+ } )
52
+ } )
47
53
. collect :: < Vec < NotificationCookie > > ( ) ,
48
54
_ => vec ! [ ] ,
49
55
}
0 commit comments