| 1 | // Copyright (c) 2019-2021 Alexander Medvednikov. All rights reserved. |
| 2 | // Use of this source code is governed by a GPL license that can be found in the LICENSE file. |
| 3 | module main |
| 4 | |
| 5 | import veb |
| 6 | import validation |
| 7 | import time |
| 8 | |
| 9 | struct Comment { |
| 10 | mut: |
| 11 | id int @[primary; sql: serial] |
| 12 | author_id int |
| 13 | issue_id int |
| 14 | created_at int |
| 15 | text string |
| 16 | } |
| 17 | |
| 18 | @['/:username/:repo_name/comments'; post] |
| 19 | pub fn (mut app App) handle_add_comment(username string, repo_name string) veb.Result { |
| 20 | app.find_repo_by_name_and_username(repo_name, username) or { return ctx.not_found() } |
| 21 | text := ctx.form['text'] |
| 22 | issue_id := ctx.form['issue_id'] |
| 23 | is_text_empty := validation.is_string_empty(text) |
| 24 | is_issue_id_empty := validation.is_string_empty(issue_id) |
| 25 | if is_text_empty || is_issue_id_empty || !ctx.logged_in { |
| 26 | ctx.error('Issue comment is not valid') |
| 27 | return app.issue(mut ctx, username, repo_name, issue_id) |
| 28 | } |
| 29 | app.add_issue_comment(ctx.user.id, issue_id.int(), text) or { |
| 30 | ctx.error('There was an error while inserting the comment') |
| 31 | return app.issue(mut ctx, username, repo_name, issue_id) |
| 32 | } |
| 33 | // TODO: count comments |
| 34 | app.increment_issue_comments(issue_id.int()) or { app.info(err.str()) } |
| 35 | return ctx.redirect('/${username}/${repo_name}/issue/${issue_id}') |
| 36 | } |
| 37 | |
| 38 | fn (mut app App) add_issue_comment(author_id int, issue_id int, text string) ! { |
| 39 | comment := Comment{ |
| 40 | author_id: author_id |
| 41 | issue_id: issue_id |
| 42 | created_at: int(time.now().unix()) |
| 43 | text: text |
| 44 | } |
| 45 | |
| 46 | sql app.db { |
| 47 | insert comment into Comment |
| 48 | }! |
| 49 | } |
| 50 | |
| 51 | fn (mut app App) get_all_issue_comments(issue_id int) []Comment { |
| 52 | comments := sql app.db { |
| 53 | select from Comment where issue_id == issue_id |
| 54 | } or { []Comment{} } |
| 55 | |
| 56 | return comments |
| 57 | } |
| 58 | |
| 59 | fn (c Comment) relative() string { |
| 60 | return time.unix(c.created_at).relative() |
| 61 | } |
| 62 | |