|
1 | 1 | package router
|
2 | 2 |
|
3 | 3 | import (
|
| 4 | + "fmt" |
4 | 5 | "net/http"
|
| 6 | + "strconv" |
5 | 7 |
|
6 | 8 | "github.com/labstack/echo/v4"
|
| 9 | + "github.com/traPtitech/booQ-v3/model" |
7 | 10 | )
|
8 | 11 |
|
9 |
| -// PostComments POST /items/:id/comments |
10 |
| -func PostComments(c echo.Context) error { |
11 |
| - return echo.NewHTTPError(http.StatusNotImplemented, "Not Implemented") |
| 12 | +type PostCommentBody struct { |
| 13 | + Text string `json:"text"` |
| 14 | +} |
| 15 | + |
| 16 | +type PostCommentResponse struct { |
| 17 | + ID int `json:"id"` |
| 18 | +} |
| 19 | + |
| 20 | +// PostComment POST /items/:id/comments |
| 21 | +func PostComment(c echo.Context) error { |
| 22 | + itemIDStr := c.Param("id") |
| 23 | + itemID, err := strconv.Atoi(itemIDStr) |
| 24 | + if err != nil { |
| 25 | + return invalidRequest(c, err) |
| 26 | + } |
| 27 | + |
| 28 | + me, err := getAuthorizedUser(c) |
| 29 | + if err != nil { |
| 30 | + return unauthorizedRequest(c, err) |
| 31 | + } |
| 32 | + |
| 33 | + var body PostCommentBody |
| 34 | + if err := c.Bind(&body); err != nil { |
| 35 | + return invalidRequest(c, err) |
| 36 | + } |
| 37 | + if body.Text == "" { |
| 38 | + return invalidRequest(c, fmt.Errorf("text is empty")) |
| 39 | + } |
| 40 | + |
| 41 | + payload := model.CreateCommentPayload{ |
| 42 | + ItemID: itemID, |
| 43 | + UserID: me, |
| 44 | + Comment: body.Text, |
| 45 | + } |
| 46 | + comment, err := model.CreateComment(&payload) |
| 47 | + if err != nil { |
| 48 | + return internalServerError(c, err) |
| 49 | + } |
| 50 | + |
| 51 | + return c.JSON(http.StatusCreated, PostCommentResponse{ID: comment.ID}) |
12 | 52 | }
|
0 commit comments