diff --git a/entities.go b/entities.go index 1d180a4..f291968 100644 --- a/entities.go +++ b/entities.go @@ -16,3 +16,8 @@ type updater interface { update(int64, *entity, Claims) error unmarshal([]byte) (entity, error) } + +type creater interface { + create(*entity, Claims) error + unmarshal([]byte) (entity, error) +} diff --git a/handlers.go b/handlers.go index bc97ce5..72b0641 100644 --- a/handlers.go +++ b/handlers.go @@ -86,6 +86,7 @@ func Handler() http.Handler { routes := []r{ r{handleLister(StrainService{}), "GET", "/strains"}, + r{handleCreater(StrainService{}), "POST", "/strains"}, r{handleGetter(StrainService{}), "GET", "/strains/{Id:.+}"}, r{handleUpdater(StrainService{}), "PUT", "/strains/{Id:.+}"}, r{handleLister(MeasurementService{}), "GET", "/measurements"}, @@ -190,6 +191,39 @@ func handleUpdater(u updater) http.HandlerFunc { } } +func handleCreater(c creater) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + bodyBytes, err := ioutil.ReadAll(r.Body) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + e, err := c.unmarshal(bodyBytes) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + con := context.Get(r, "claims") + var claims Claims = con.(Claims) + + err = c.create(&e, claims) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + data, err := e.marshal() + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "application/json; charset=UTF-8") + w.Write(data) + } +} + func tokenHandler(h http.Handler) http.Handler { token := func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json; charset=UTF-8") diff --git a/strains.go b/strains.go index 5f8c932..f772b01 100644 --- a/strains.go +++ b/strains.go @@ -136,3 +136,17 @@ func (s StrainService) update(id int64, e *entity, claims Claims) error { } return nil } + +func (s StrainService) create(e *entity, claims Claims) error { + strain := (*e).(*Strain) + ct := currentTime() + strain.CreatedBy = claims.Sub + strain.CreatedAt = ct + strain.UpdatedBy = claims.Sub + strain.UpdatedAt = ct + + if err := DBH.Insert(strain.StrainBase); err != nil { + return err + } + return nil +}