/
route_append_comment.go
109 lines (98 loc) · 2.82 KB
/
route_append_comment.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package http
import (
"context"
"encoding/json"
"net/http"
"github.com/Ptt-official-app/Ptt-backend/internal/repository"
"github.com/Ptt-official-app/Ptt-backend/internal/usecase"
)
// appendComment handles request with `/v1/boards/{boardID}/articles/{filename}` and will
// add comment to the article
func (delivery *Delivery) appendComment(w http.ResponseWriter, r *http.Request, boardID, filename string) {
delivery.logger.Debugf("appendComment: %v", r)
appendType := r.PostFormValue("type")
text := r.PostFormValue("text")
updateUsefulness := false
if appendType == "↑" || appendType == "↓" {
updateUsefulness = true
}
if appendType == "" || (!updateUsefulness && text == "") {
w.WriteHeader(500)
return
}
token := delivery.getTokenFromRequest(r)
userID, err := delivery.usecase.GetUserIDFromToken(token)
if err != nil {
w.WriteHeader(http.StatusUnauthorized)
return
}
ctx := context.Background()
// Check permission for append comment
err = delivery.usecase.CheckPermission(token, []usecase.Permission{usecase.PermissionAppendComment}, map[string]string{
"board_id": boardID,
"article_id": filename,
"user_id": userID,
})
if err != nil {
// TODO: record unauthorized access
w.WriteHeader(http.StatusUnauthorized)
return
}
var res repository.PushRecord
if updateUsefulness {
res, err = delivery.usecase.UpdateUsefulness(
ctx,
userID,
boardID,
filename,
appendType,
)
} else {
res, err = delivery.usecase.AppendComment(
ctx,
userID,
boardID,
filename,
appendType,
text,
)
}
if err != nil {
w.WriteHeader(http.StatusBadRequest)
m := map[string]string{
"error": "append_comment_error",
"error_description": err.Error(),
}
b, _ := json.MarshalIndent(m, "", " ")
_, err = w.Write(b)
if err != nil {
delivery.logger.Errorf("AppendComment error response err: %w", err)
}
return
}
responseMap := map[string]interface{}{
"data": map[string]interface{}{
"raw": r.PostForm.Encode(),
"parsed": map[string]interface{}{
"is_header_modied": false,
"author_id": nil,
"author_name": nil,
"title": nil,
"post_time": nil,
"board_name": "", // todo: go-bbs articles 需實作新介面取得資訊
"text": map[string]string{
"text": "", // todo: // todo: go-bbs articles 需實作新介面取得資訊
},
"signature": map[string]string{},
"sender_info": map[string]string{}, // todo: go-bbs articles 需實作新介面取得資訊(user info)
"edit_records": map[string]string{},
"push_records": []repository.PushRecord{res}, // TODO: support bbs.PushRecord instead
},
},
}
b, _ := json.MarshalIndent(responseMap, "", " ")
_, err = w.Write(b)
if err != nil {
delivery.logger.Errorf("getBoardTreasures write success response err: %w", err)
}
}