a mini social media app for small communities
1module database
2
3import entity { Notification }
4
5// get_notification_by_id gets a notification by its given id, returns none if
6// the notification does not exist.
7pub fn (app &DatabaseAccess) get_notification_by_id(id int) ?Notification {
8 notifications := sql app.db {
9 select from Notification where id == id
10 } or { [] }
11 if notifications.len != 1 {
12 return none
13 }
14 return notifications[0]
15}
16
17// delete_notification deletes the given notification, returns true if this
18// succeeded and false otherwise.
19pub fn (app &DatabaseAccess) delete_notification(id int) bool {
20 sql app.db {
21 delete from Notification where id == id
22 } or {
23 return false
24 }
25 return true
26}
27
28// delete_notifications_for_user deletes all notifications for the given user,
29// returns true if this succeeded and false otherwise.
30pub fn (app &DatabaseAccess) delete_notifications_for_user(user_id int) bool {
31 sql app.db {
32 delete from Notification where user_id == user_id
33 } or {
34 return false
35 }
36 return true
37}
38
39// get_notifications_for gets a list of notifications for the given user.
40pub fn (app &DatabaseAccess) get_notifications_for(user_id int) []Notification {
41 notifications := sql app.db {
42 select from Notification where user_id == user_id
43 } or { [] }
44 return notifications
45}
46
47// get_notification_count gets the amount of notifications a user has, with a
48// given limit.
49pub fn (app &DatabaseAccess) get_notification_count(user_id int, limit int) int {
50 notifications := app.db.exec_param2('SELECT id FROM "Notification" WHERE user_id = $1 LIMIT $2', user_id.str(), limit.str()) or { [] }
51 return notifications.len
52}
53
54// send_notification_to sends a notification to the given user.
55pub fn (app &DatabaseAccess) send_notification_to(user_id int, summary string, body string) {
56 notification := Notification{
57 user_id: user_id
58 summary: summary
59 body: body
60 }
61 sql app.db {
62 insert notification into Notification
63 } or {
64 eprintln('failed to send notification ${notification}')
65 }
66}