ggdgsdbsdbbb / repo / watch.v
56 lines · 45 sloc · 1.22 KB · a449238961bbd5f9081831ef9db1ac936909a3e8
Raw
1module main
2
3struct Watch {
4 id int @[primary; sql: serial]
5 user_id int @[unique: 'repo_watch']
6 repo_id int @[unique: 'repo_watch']
7}
8
9fn (mut app App) watch_repo(repo_id int, user_id int) ! {
10 watch := Watch{
11 repo_id: repo_id
12 user_id: user_id
13 }
14
15 sql app.db {
16 insert watch into Watch
17 }!
18}
19
20fn (mut app App) get_count_repo_watchers(repo_id int) int {
21 return sql app.db {
22 select count from Watch where repo_id == repo_id
23 } or { 0 }
24}
25
26fn (mut app App) find_watching_repo_ids(user_id int) []int {
27 watch_list := sql app.db {
28 select from Watch where user_id == user_id
29 } or { [] }
30
31 return watch_list.map(it.repo_id)
32}
33
34fn (mut app App) toggle_repo_watcher_status(repo_id int, user_id int) ! {
35 is_watching := app.check_repo_watcher_status(repo_id, user_id)
36
37 if is_watching {
38 app.unwatch_repo(repo_id, user_id)!
39 } else {
40 app.watch_repo(repo_id, user_id)!
41 }
42}
43
44fn (mut app App) check_repo_watcher_status(repo_id int, user_id int) bool {
45 watches := sql app.db {
46 select from Watch where repo_id == repo_id && user_id == user_id limit 1
47 } or { [] }
48
49 return watches.len != 0
50}
51
52fn (mut app App) unwatch_repo(repo_id int, user_id int) ! {
53 sql app.db {
54 delete from Watch where repo_id == repo_id && user_id == user_id
55 }!
56}
57