-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler_review.go
55 lines (44 loc) · 1.32 KB
/
handler_review.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
package main
import (
"net/http"
"github.com/gorilla/mux"
"github.com/kiambogo/coffeeworks/models"
"github.com/kiambogo/coffeeworks/support"
)
// CreateReview handles requests to create new reviews against a cafe
func CreateReview(w http.ResponseWriter, r *http.Request) {
form := &models.CreateReviewForm{}
err := support.UnmarshalJSON(r.Body, form)
if err != nil {
support.ReturnString(w, 400, "Invalid data passed for CreateReviewForm")
return
}
validationErrors := form.Validate()
if len(validationErrors) > 0 {
support.ReturnJSON(w, 400, validationErrors)
return
}
review := &models.Review{}
review.LoadFromCreateForm(*form)
if err := models.DB.Create(review).Error; err != nil {
support.LogError(err, "CreateReview - saving review to db")
return
}
// Asynchronously process the review
go ProcessReview(review)
support.ReturnPrettyJSON(w, 200, form)
}
// GetReview handles requests to retrieve a review by place ID
func GetReview(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
placeID, ok := vars["id"]
if !ok {
support.ReturnString(w, 400, "Place ID required")
}
reviews := &models.Reviews{}
if err := models.DB.Where("place_id = ?", placeID).Find(&reviews).Error; err != nil {
support.LogError(err, "GetReview (%v)", placeID)
return
}
support.ReturnPrettyJSON(w, 200, reviews)
}