a mini social media app for small communities
1module database
2
3import entity { Like, LikeCache }
4
5// add_like adds a like to the database, returns true if this succeeds and false
6// otherwise.
7pub fn (app &DatabaseAccess) add_like(like &Like) bool {
8 sql app.db {
9 insert like into Like
10 // yeet the old cached like value
11 delete from LikeCache where post_id == like.post_id
12 } or {
13 return false
14 }
15 return true
16}
17
18// get_net_likes_for_post returns the net likes of the given post.
19pub fn (app &DatabaseAccess) get_net_likes_for_post(post_id int) int {
20 // check cache
21 cache := sql app.db {
22 select from LikeCache where post_id == post_id limit 1
23 } or { [] }
24
25 mut likes := 0
26
27 if cache.len != 1 {
28 println('calculating net likes for post: ${post_id}')
29 // calculate
30 db_likes := sql app.db {
31 select from Like where post_id == post_id
32 } or { [] }
33
34 for like in db_likes {
35 if like.is_like {
36 likes++
37 } else {
38 likes--
39 }
40 }
41
42 // cache
43 cached := LikeCache{
44 post_id: post_id
45 likes: likes
46 }
47 sql app.db {
48 insert cached into LikeCache
49 } or {
50 eprintln('failed to cache like: ${cached}')
51 return likes
52 }
53 } else {
54 likes = cache.first().likes
55 }
56
57 return likes
58}
59
60// unlike_post removes a (dis)like from the given post, returns true if this
61// succeeds and false otherwise.
62pub fn (app &DatabaseAccess) unlike_post(post_id int, user_id int) bool {
63 sql app.db {
64 delete from Like where user_id == user_id && post_id == post_id
65 // yeet the old cached like value
66 delete from LikeCache where post_id == post_id
67 } or {
68 return false
69 }
70 return true
71}