@@ -3,11 +3,36 @@ use crate::{
3
3
custom:: error:: CustomError ,
4
4
models:: notification_model:: Notification ,
5
5
} ;
6
- use mongodb:: { bson:: doc, sync:: Collection } ;
6
+ use mongodb:: {
7
+ bson:: { doc, oid:: ObjectId } ,
8
+ sync:: Collection ,
9
+ } ;
7
10
use rocket:: { http:: Status , serde:: json:: Json , State } ;
8
11
12
+ fn NOTIF_NOT_FOUND ( id : String ) -> String {
13
+ format ! ( "Notification with id {} not found" , id)
14
+ }
15
+
9
16
impl MongoRepo {
10
- pub fn get_notifications ( & self ) -> Result < Vec < Notification > , String > {
17
+ pub fn get_notification ( & self , id : & String ) -> Result < Notification , String > {
18
+ let obj_id = match ObjectId :: parse_str ( id) {
19
+ Ok ( i) => i,
20
+ Err ( error) => return Err ( error. to_string ( ) ) ,
21
+ } ;
22
+
23
+ let filter = doc ! { "_id" : obj_id} ;
24
+ let col: Collection < Notification > = self . db . collection ( "notifications" ) ;
25
+ let notification = match col. find_one ( filter, None ) . ok ( ) {
26
+ Some ( n) => n,
27
+ None => return Err ( DB_CON_ERR . to_string ( ) ) ,
28
+ } ;
29
+ match notification {
30
+ Some ( n) => Ok ( n) ,
31
+ None => Err ( NOTIF_NOT_FOUND ( obj_id. to_string ( ) ) ) ,
32
+ }
33
+ }
34
+
35
+ pub fn get_all_notifications ( & self ) -> Result < Vec < Notification > , String > {
11
36
let col: Collection < Notification > = self . db . collection ( "notifications" ) ;
12
37
let cursors = match col. find ( None , None ) . ok ( ) {
13
38
Some ( c) => c,
@@ -18,9 +43,36 @@ impl MongoRepo {
18
43
}
19
44
}
20
45
46
+ #[ get( "/notification/<path>" ) ]
47
+ pub fn get_notification (
48
+ db : & State < MongoRepo > ,
49
+ path : String ,
50
+ ) -> Result < Json < Notification > , CustomError > {
51
+ let id = path;
52
+ if id. is_empty ( ) {
53
+ return Err ( CustomError :: Default ( Status :: BadRequest ) ) ;
54
+ } ;
55
+ let notification = db. get_notification ( & id) ;
56
+ match notification {
57
+ Ok ( notification) => Ok ( Json ( notification) ) ,
58
+ Err ( error) => {
59
+ if error == NOTIF_NOT_FOUND ( id) {
60
+ Err ( CustomError :: ServiceUnavailable ( Status :: BadRequest , error) )
61
+ } else {
62
+ Err ( CustomError :: ServiceUnavailable (
63
+ Status :: ServiceUnavailable ,
64
+ error,
65
+ ) )
66
+ }
67
+ }
68
+ }
69
+ }
70
+
21
71
#[ get( "/notifications" ) ]
22
- pub fn get_notifications ( db : & State < MongoRepo > ) -> Result < Json < Vec < Notification > > , CustomError > {
23
- let notifications = db. get_notifications ( ) ;
72
+ pub fn get_all_notifications (
73
+ db : & State < MongoRepo > ,
74
+ ) -> Result < Json < Vec < Notification > > , CustomError > {
75
+ let notifications = db. get_all_notifications ( ) ;
24
76
match notifications {
25
77
Ok ( notifications) => {
26
78
if notifications. is_empty ( ) {
0 commit comments