-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcreate_member.go
More file actions
68 lines (54 loc) · 1.63 KB
/
create_member.go
File metadata and controls
68 lines (54 loc) · 1.63 KB
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
package handler
import (
"encoding/json"
"fmt"
"net/http"
api "github.com/dxta-dev/app/internal/internal-api"
"github.com/dxta-dev/app/internal/util"
)
type CreateMemberRequestBody struct {
Name string `json:"name"`
Email *string `json:"email"`
}
type CreateMemberResponse struct {
MemberId int64 `json:"member_id"`
}
func CreateMember(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
body := &CreateMemberRequestBody{}
if err := json.NewDecoder(r.Body).Decode(body); err != nil {
fmt.Printf("Issue while parsing body. Error: %s", err.Error())
util.JSONError(w, util.ErrorParam{Error: "Bad Request"}, http.StatusBadRequest)
return
}
if body.Name == "" {
fmt.Println("No member name in request body")
util.JSONError(w, util.ErrorParam{Error: "Bad Request"}, http.StatusBadRequest)
}
authId := ctx.Value(util.AuthIdCtxKey).(string)
apiState, err := api.InternalApiState(authId, ctx)
if err != nil {
util.JSONError(w, util.ErrorParam{Error: "Internal Server Error"}, http.StatusInternalServerError)
return
}
newMemberRes, err := apiState.DB.CreateMember(body.Name, body.Email, ctx)
if err != nil {
util.JSONError(
w,
util.ErrorParam{Error: "Could not create new member"},
http.StatusInternalServerError,
)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(CreateMemberResponse{MemberId: newMemberRes.Id}); err != nil {
fmt.Printf("Issue while formatting response. Error: %s", err.Error())
util.JSONError(
w,
util.ErrorParam{Error: "Internal Server Error"},
http.StatusInternalServerError,
)
return
}
}