| 1 | module main |
| 2 | |
| 3 | struct Watch { |
| 4 | id int @[primary; sql: serial] |
| 5 | user_id int @[unique: 'repo_watch'] |
| 6 | repo_id int @[unique: 'repo_watch'] |
| 7 | } |
| 8 | |
| 9 | fn (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 | |
| 20 | fn (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 | |
| 26 | fn (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 | |
| 34 | fn (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 | |
| 44 | fn (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 | |
| 52 | fn (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 | |