Create strain

This commit is contained in:
Matthew Dillon 2015-06-03 11:22:06 -08:00
parent 232394ea8a
commit ed1f795a01
3 changed files with 53 additions and 0 deletions

View file

@ -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)
}

View file

@ -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")

View file

@ -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
}