/
recipeHandler.go
100 lines (90 loc) · 2.39 KB
/
recipeHandler.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
package api
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/alexbaily/KitchenHelper-backend/models"
"github.com/gorilla/mux"
)
/*
HTTP handler for post requests on /recipes
*/
func recipeGetHandler(w http.ResponseWriter, r *http.Request) {
//retrieve the UserID variable
uuid := getUserID(r.Context().Value("user"))
recipe := mux.Vars(r)["recipe"]
dataJson, err := DynaDB.queryRecipes(uuid, recipe, recipeTable)
if err != nil {
panic(fmt.Sprintf("failed to get recipe, %v", err))
w.Header().Add("statusDescription", "500 Internal Server Error")
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("500 Internal Server Error"))
return
}
//Set response headers.
w.Header().Add("statusDescription", "200 OK")
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(dataJson)
return
}
/*
recipePostHandler will take a JSON document, parse and then add to the DB.
JSON syntax:
{
Name,
Description,
Ingredients : [
{
Name,
Quantity,
Measurement
}
],
Steps: [
{
ID,
Text,
ImgURL
}
],
Notes,
Sharing
}
*/
func recipePostHandler(w http.ResponseWriter, r *http.Request) {
//retrieve the UserID variable
uuid := getUserID(r.Context().Value("user"))
recipeJson, err := ioutil.ReadAll(r.Body)
//If we can't find the correct parameter then return a status 400.
if err != nil {
fmt.Println("Error reading from the request body.")
w.Header().Add("statusDescription", "500 Internal Server Error")
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("500 Internal Server Error"))
return
}
recipe := models.RecipeRecord{}
err = json.Unmarshal(recipeJson, &recipe)
if err != nil {
panic(fmt.Sprintf("failed to unmarshal Dynamodb Scan Items, %v", err))
w.Header().Add("statusDescription", "500 Internal Server Error")
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("500 Internal Server Error"))
return
}
err = DynaDB.addRecipe(uuid, recipe, recipeTable)
if err != nil {
panic(fmt.Sprintf("failed to add recipe, %v", err))
w.Header().Add("statusDescription", "500 Internal Server Error")
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("500 Internal Server Error"))
return
}
//Set response headers.
w.Header().Add("statusDescription", "200 OK")
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
return
}