Garden objects backend: polymorphic CRUD + /full endpoint (#10) #28
+1
-1
@@ -81,7 +81,7 @@ func New(cfg *config.Config, svc *service.Service) *gin.Engine {
|
|||||||
gardens.GET("/:id", h.getGarden)
|
gardens.GET("/:id", h.getGarden)
|
||||||
gardens.PATCH("/:id", h.updateGarden)
|
gardens.PATCH("/:id", h.updateGarden)
|
||||||
gardens.DELETE("/:id", h.deleteGarden)
|
gardens.DELETE("/:id", h.deleteGarden)
|
||||||
gardens.GET("/:id/full", h.gardenFull) // one-shot editor load
|
gardens.GET("/:id/full", h.getGardenFull) // one-shot editor load
|
||||||
gardens.POST("/:id/objects", h.createObject)
|
gardens.POST("/:id/objects", h.createObject)
|
||||||
|
|
||||||
// Objects are addressed by their own id; the service resolves the owning
|
// Objects are addressed by their own id; the service resolves the owning
|
||||||
|
|||||||
@@ -20,13 +20,14 @@ func registerAndCookie(t *testing.T, r *gin.Engine, email string) *http.Cookie {
|
|||||||
return sessionCookieFrom(t, w)
|
return sessionCookieFrom(t, w)
|
||||||
}
|
}
|
||||||
|
|
||||||
func decodeGarden(t *testing.T, body []byte) map[string]any {
|
// decodeMap unmarshals any JSON object response into a generic map.
|
||||||
|
func decodeMap(t *testing.T, body []byte) map[string]any {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
var g map[string]any
|
var m map[string]any
|
||||||
if err := json.Unmarshal(body, &g); err != nil {
|
if err := json.Unmarshal(body, &m); err != nil {
|
||||||
t.Fatalf("decode garden: %v (body %s)", err, body)
|
t.Fatalf("decode json object: %v (body %s)", err, body)
|
||||||
}
|
}
|
||||||
return g
|
return m
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestGardenCRUDFlow(t *testing.T) {
|
func TestGardenCRUDFlow(t *testing.T) {
|
||||||
@@ -38,7 +39,7 @@ func TestGardenCRUDFlow(t *testing.T) {
|
|||||||
if w.Code != http.StatusCreated {
|
if w.Code != http.StatusCreated {
|
||||||
t.Fatalf("create status = %d, body %s", w.Code, w.Body.String())
|
t.Fatalf("create status = %d, body %s", w.Code, w.Body.String())
|
||||||
}
|
}
|
||||||
created := decodeGarden(t, w.Body.Bytes())
|
created := decodeMap(t, w.Body.Bytes())
|
||||||
id := int64(created["id"].(float64))
|
id := int64(created["id"].(float64))
|
||||||
if created["widthCm"].(float64) != 1000 || created["unitPref"].(string) != "metric" {
|
if created["widthCm"].(float64) != 1000 || created["unitPref"].(string) != "metric" {
|
||||||
t.Errorf("defaults not applied: %+v", created)
|
t.Errorf("defaults not applied: %+v", created)
|
||||||
@@ -69,7 +70,7 @@ func TestGardenCRUDFlow(t *testing.T) {
|
|||||||
if w.Code != http.StatusOK {
|
if w.Code != http.StatusOK {
|
||||||
t.Fatalf("patch status = %d, body %s", w.Code, w.Body.String())
|
t.Fatalf("patch status = %d, body %s", w.Code, w.Body.String())
|
||||||
}
|
}
|
||||||
patched := decodeGarden(t, w.Body.Bytes())
|
patched := decodeMap(t, w.Body.Bytes())
|
||||||
if patched["name"].(string) != "Front" || patched["version"].(float64) != 2 {
|
if patched["name"].(string) != "Front" || patched["version"].(float64) != 2 {
|
||||||
t.Errorf("patch didn't persist/bump: %+v", patched)
|
t.Errorf("patch didn't persist/bump: %+v", patched)
|
||||||
}
|
}
|
||||||
@@ -90,7 +91,7 @@ func TestGardenVersionConflictEnvelope(t *testing.T) {
|
|||||||
cookie := registerAndCookie(t, r, "[email protected]")
|
cookie := registerAndCookie(t, r, "[email protected]")
|
||||||
|
|
||||||
w := doJSON(t, r, http.MethodPost, "/api/v1/gardens", map[string]any{"name": "Yard"}, cookie)
|
w := doJSON(t, r, http.MethodPost, "/api/v1/gardens", map[string]any{"name": "Yard"}, cookie)
|
||||||
id := int64(decodeGarden(t, w.Body.Bytes())["id"].(float64))
|
id := int64(decodeMap(t, w.Body.Bytes())["id"].(float64))
|
||||||
|
|
||||||
body := map[string]any{"name": "Yard2", "widthCm": 1000, "heightCm": 1000, "unitPref": "metric", "version": 1}
|
body := map[string]any{"name": "Yard2", "widthCm": 1000, "heightCm": 1000, "unitPref": "metric", "version": 1}
|
||||||
// First patch at version 1 succeeds (→ version 2).
|
// First patch at version 1 succeeds (→ version 2).
|
||||||
@@ -123,7 +124,7 @@ func TestGardenCrossUserIsNotFound(t *testing.T) {
|
|||||||
bob := registerAndCookie(t, r, "[email protected]")
|
bob := registerAndCookie(t, r, "[email protected]")
|
||||||
|
|
||||||
w := doJSON(t, r, http.MethodPost, "/api/v1/gardens", map[string]any{"name": "Alice's"}, alice)
|
w := doJSON(t, r, http.MethodPost, "/api/v1/gardens", map[string]any{"name": "Alice's"}, alice)
|
||||||
id := int64(decodeGarden(t, w.Body.Bytes())["id"].(float64))
|
id := int64(decodeMap(t, w.Body.Bytes())["id"].(float64))
|
||||||
|
|
||||||
// Bob sees a 404 (existence masked), not a 403.
|
// Bob sees a 404 (existence masked), not a 403.
|
||||||
if w := doJSON(t, r, http.MethodGet, gardenPath(id), nil, bob); w.Code != http.StatusNotFound {
|
if w := doJSON(t, r, http.MethodGet, gardenPath(id), nil, bob); w.Code != http.StatusNotFound {
|
||||||
@@ -166,7 +167,7 @@ func TestGardenUpdateRejectsBadVersion(t *testing.T) {
|
|||||||
r := authEngine(t, localCfg())
|
r := authEngine(t, localCfg())
|
||||||
cookie := registerAndCookie(t, r, "[email protected]")
|
cookie := registerAndCookie(t, r, "[email protected]")
|
||||||
w := doJSON(t, r, http.MethodPost, "/api/v1/gardens", map[string]any{"name": "Yard"}, cookie)
|
w := doJSON(t, r, http.MethodPost, "/api/v1/gardens", map[string]any{"name": "Yard"}, cookie)
|
||||||
id := int64(decodeGarden(t, w.Body.Bytes())["id"].(float64))
|
id := int64(decodeMap(t, w.Body.Bytes())["id"].(float64))
|
||||||
|
|
||||||
// A negative (or zero) version is invalid input (400), not a version conflict.
|
// A negative (or zero) version is invalid input (400), not a version conflict.
|
||||||
for _, v := range []int{0, -1} {
|
for _, v := range []int{0, -1} {
|
||||||
|
|||||||
+66
-37
@@ -30,9 +30,19 @@ type objectCreateRequest struct {
|
|||||||
Notes string `json:"notes"`
|
Notes string `json:"notes"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (r objectCreateRequest) toInput() service.ObjectInput {
|
||||||
|
return service.ObjectInput{
|
||||||
|
Kind: r.Kind, Name: r.Name, Shape: r.Shape,
|
||||||
|
XCM: r.XCM, YCM: r.YCM, WidthCM: r.WidthCM, HeightCM: r.HeightCM,
|
||||||
|
RotationDeg: r.RotationDeg, ZIndex: r.ZIndex, Plantable: r.Plantable,
|
||||||
|
Color: r.Color, Props: propsFromRaw(r.Props), Notes: r.Notes,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// objectUpdateRequest is the body for PATCH /objects/:id: every field optional
|
// objectUpdateRequest is the body for PATCH /objects/:id: every field optional
|
||||||
// (absent = unchanged), plus the required current version. Kind and shape are
|
// (absent = unchanged), plus the required current version. Kind and shape are
|
||||||
// immutable and not accepted.
|
// immutable and not accepted. color/props are json.RawMessage so an explicit
|
||||||
|
// null (clear the override) is distinguishable from an absent field (unchanged).
|
||||||
type objectUpdateRequest struct {
|
type objectUpdateRequest struct {
|
||||||
Name *string `json:"name"`
|
Name *string `json:"name"`
|
||||||
XCM *float64 `json:"xCm"`
|
XCM *float64 `json:"xCm"`
|
||||||
@@ -42,20 +52,60 @@ type objectUpdateRequest struct {
|
|||||||
RotationDeg *float64 `json:"rotationDeg"`
|
RotationDeg *float64 `json:"rotationDeg"`
|
||||||
ZIndex *int `json:"zIndex"`
|
ZIndex *int `json:"zIndex"`
|
||||||
Plantable *bool `json:"plantable"`
|
Plantable *bool `json:"plantable"`
|
||||||
Color *string `json:"color"`
|
Color json.RawMessage `json:"color"`
|
||||||
Props json.RawMessage `json:"props"`
|
Props json.RawMessage `json:"props"`
|
||||||
Notes *string `json:"notes"`
|
Notes *string `json:"notes"`
|
||||||
Version int64 `json:"version" binding:"required,min=1"`
|
Version int64 `json:"version" binding:"required,min=1"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// propsFromRaw maps a JSON props value to the stored *string: a present, non-null
|
func (r objectUpdateRequest) toPatch() (service.ObjectPatch, error) {
|
||||||
// value becomes its JSON text; absent or null becomes nil (leave/none).
|
color, setColor, err := parseNullableString(r.Color)
|
||||||
|
if err != nil {
|
||||||
|
return service.ObjectPatch{}, err
|
||||||
|
}
|
||||||
|
props, setProps := parseNullableJSON(r.Props)
|
||||||
|
return service.ObjectPatch{
|
||||||
|
Name: r.Name, XCM: r.XCM, YCM: r.YCM, WidthCM: r.WidthCM, HeightCM: r.HeightCM,
|
||||||
|
RotationDeg: r.RotationDeg, ZIndex: r.ZIndex, Plantable: r.Plantable,
|
||||||
|
SetColor: setColor, Color: color, SetProps: setProps, Props: props, Notes: r.Notes,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// propsFromRaw maps a JSON props value to the stored *string for create: a
|
||||||
|
// present, non-null value becomes its JSON text; absent or null becomes nil.
|
||||||
func propsFromRaw(raw json.RawMessage) *string {
|
func propsFromRaw(raw json.RawMessage) *string {
|
||||||
if len(raw) == 0 || string(raw) == "null" {
|
v, set := parseNullableJSON(raw)
|
||||||
|
if !set {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
|
||||||
|
// parseNullableString decodes a JSON string|null field into (value, present).
|
||||||
|
// Absent → (nil, false); null → (nil, true); "x" → (&"x", true). A non-string
|
||||||
|
// value is an error.
|
||||||
|
func parseNullableString(raw json.RawMessage) (value *string, present bool, err error) {
|
||||||
|
if len(raw) == 0 {
|
||||||
|
return nil, false, nil
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(raw, &value); err != nil {
|
||||||
|
return nil, false, err
|
||||||
|
}
|
||||||
|
return value, true, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// parseNullableJSON decodes any JSON value into (text, present) for a nullable
|
||||||
|
// TEXT column. Absent → (nil, false); null → (nil, true); anything else → the
|
||||||
|
// raw JSON text (&, true).
|
||||||
|
func parseNullableJSON(raw json.RawMessage) (value *string, present bool) {
|
||||||
|
if len(raw) == 0 {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
if string(raw) == "null" {
|
||||||
|
return nil, true
|
||||||
|
}
|
||||||
s := string(raw)
|
s := string(raw)
|
||||||
return &s
|
return &s, true
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *handlers) createObject(c *gin.Context) {
|
func (h *handlers) createObject(c *gin.Context) {
|
||||||
@@ -65,24 +115,10 @@ func (h *handlers) createObject(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
var req objectCreateRequest
|
var req objectCreateRequest
|
||||||
if err := c.ShouldBindJSON(&req); err != nil {
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
writeAPIError(c, http.StatusBadRequest, "INVALID_INPUT", "kind is required")
|
writeAPIError(c, http.StatusBadRequest, "INVALID_INPUT", "invalid object: kind is required")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
o, err := h.svc.CreateObject(c.Request.Context(), mustActor(c).ID, gardenID, service.ObjectInput{
|
o, err := h.svc.CreateObject(c.Request.Context(), mustActor(c).ID, gardenID, req.toInput())
|
||||||
Kind: req.Kind,
|
|
||||||
Name: req.Name,
|
|
||||||
Shape: req.Shape,
|
|
||||||
XCM: req.XCM,
|
|
||||||
YCM: req.YCM,
|
|
||||||
WidthCM: req.WidthCM,
|
|
||||||
HeightCM: req.HeightCM,
|
|
||||||
RotationDeg: req.RotationDeg,
|
|
||||||
ZIndex: req.ZIndex,
|
|
||||||
Plantable: req.Plantable,
|
|
||||||
Color: req.Color,
|
|
||||||
Props: propsFromRaw(req.Props),
|
|
||||||
Notes: req.Notes,
|
|
||||||
})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writeServiceError(c, err)
|
writeServiceError(c, err)
|
||||||
return
|
return
|
||||||
@@ -97,22 +133,15 @@ func (h *handlers) updateObject(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
var req objectUpdateRequest
|
var req objectUpdateRequest
|
||||||
if err := c.ShouldBindJSON(&req); err != nil {
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
writeAPIError(c, http.StatusBadRequest, "INVALID_INPUT", "a current version is required")
|
writeAPIError(c, http.StatusBadRequest, "INVALID_INPUT", "invalid update: a current version is required")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
o, err := h.svc.UpdateObject(c.Request.Context(), mustActor(c).ID, id, service.ObjectPatch{
|
patch, err := req.toPatch()
|
||||||
Name: req.Name,
|
if err != nil {
|
||||||
XCM: req.XCM,
|
writeAPIError(c, http.StatusBadRequest, "INVALID_INPUT", "invalid update payload")
|
||||||
YCM: req.YCM,
|
return
|
||||||
WidthCM: req.WidthCM,
|
}
|
||||||
HeightCM: req.HeightCM,
|
o, err := h.svc.UpdateObject(c.Request.Context(), mustActor(c).ID, id, patch, req.Version)
|
||||||
RotationDeg: req.RotationDeg,
|
|
||||||
ZIndex: req.ZIndex,
|
|
||||||
Plantable: req.Plantable,
|
|
||||||
Color: req.Color,
|
|
||||||
Props: propsFromRaw(req.Props),
|
|
||||||
Notes: req.Notes,
|
|
||||||
}, req.Version)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, domain.ErrVersionConflict) {
|
if errors.Is(err, domain.ErrVersionConflict) {
|
||||||
writeVersionConflict(c, o)
|
writeVersionConflict(c, o)
|
||||||
@@ -136,7 +165,7 @@ func (h *handlers) deleteObject(c *gin.Context) {
|
|||||||
c.Status(http.StatusNoContent)
|
c.Status(http.StatusNoContent)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *handlers) gardenFull(c *gin.Context) {
|
func (h *handlers) getGardenFull(c *gin.Context) {
|
||||||
gardenID, ok := parseIDParam(c, "id")
|
gardenID, ok := parseIDParam(c, "id")
|
||||||
if !ok {
|
if !ok {
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ func createGardenAPI(t *testing.T, r *gin.Engine, cookie *http.Cookie, name stri
|
|||||||
if w.Code != http.StatusCreated {
|
if w.Code != http.StatusCreated {
|
||||||
t.Fatalf("create garden: status %d, body %s", w.Code, w.Body.String())
|
t.Fatalf("create garden: status %d, body %s", w.Code, w.Body.String())
|
||||||
}
|
}
|
||||||
return int64(decodeGarden(t, w.Body.Bytes())["id"].(float64))
|
return int64(decodeMap(t, w.Body.Bytes())["id"].(float64))
|
||||||
}
|
}
|
||||||
|
|
||||||
func objectPath(id int64) string { return "/api/v1/objects/" + strconv.FormatInt(id, 10) }
|
func objectPath(id int64) string { return "/api/v1/objects/" + strconv.FormatInt(id, 10) }
|
||||||
@@ -36,7 +36,7 @@ func TestObjectCRUDAndFull(t *testing.T) {
|
|||||||
if w.Code != http.StatusCreated {
|
if w.Code != http.StatusCreated {
|
||||||
t.Fatalf("create object: status %d, body %s", w.Code, w.Body.String())
|
t.Fatalf("create object: status %d, body %s", w.Code, w.Body.String())
|
||||||
}
|
}
|
||||||
obj := decodeGarden(t, w.Body.Bytes())
|
obj := decodeMap(t, w.Body.Bytes())
|
||||||
oid := int64(obj["id"].(float64))
|
oid := int64(obj["id"].(float64))
|
||||||
|
|
|||||||
if obj["plantable"].(bool) != true {
|
if obj["plantable"].(bool) != true {
|
||||||
t.Error("bed should default plantable=true")
|
t.Error("bed should default plantable=true")
|
||||||
@@ -68,7 +68,7 @@ func TestObjectCRUDAndFull(t *testing.T) {
|
|||||||
if w.Code != http.StatusOK {
|
if w.Code != http.StatusOK {
|
||||||
t.Fatalf("patch: status %d, body %s", w.Code, w.Body.String())
|
t.Fatalf("patch: status %d, body %s", w.Code, w.Body.String())
|
||||||
}
|
}
|
||||||
patched := decodeGarden(t, w.Body.Bytes())
|
patched := decodeMap(t, w.Body.Bytes())
|
||||||
if patched["xCm"].(float64) != 500 || patched["version"].(float64) != 2 {
|
if patched["xCm"].(float64) != 500 || patched["version"].(float64) != 2 {
|
||||||
t.Errorf("patch didn't apply/bump: %+v", patched)
|
t.Errorf("patch didn't apply/bump: %+v", patched)
|
||||||
}
|
}
|
||||||
@@ -90,7 +90,7 @@ func TestObjectVersionConflict(t *testing.T) {
|
|||||||
gid := createGardenAPI(t, r, cookie, "Yard")
|
gid := createGardenAPI(t, r, cookie, "Yard")
|
||||||
w := doJSON(t, r, http.MethodPost, objectsPath(gid),
|
w := doJSON(t, r, http.MethodPost, objectsPath(gid),
|
||||||
map[string]any{"kind": "bed", "xCm": 300, "yCm": 300, "widthCm": 100, "heightCm": 100}, cookie)
|
map[string]any{"kind": "bed", "xCm": 300, "yCm": 300, "widthCm": 100, "heightCm": 100}, cookie)
|
||||||
oid := int64(decodeGarden(t, w.Body.Bytes())["id"].(float64))
|
oid := int64(decodeMap(t, w.Body.Bytes())["id"].(float64))
|
||||||
|
|
||||||
body := map[string]any{"xCm": 400, "version": 1}
|
body := map[string]any{"xCm": 400, "version": 1}
|
||||||
if w := doJSON(t, r, http.MethodPatch, objectPath(oid), body, cookie); w.Code != http.StatusOK {
|
if w := doJSON(t, r, http.MethodPatch, objectPath(oid), body, cookie); w.Code != http.StatusOK {
|
||||||
@@ -117,7 +117,7 @@ func TestObjectCrossUserIsNotFound(t *testing.T) {
|
|||||||
gid := createGardenAPI(t, r, alice, "Alice's")
|
gid := createGardenAPI(t, r, alice, "Alice's")
|
||||||
w := doJSON(t, r, http.MethodPost, objectsPath(gid),
|
w := doJSON(t, r, http.MethodPost, objectsPath(gid),
|
||||||
map[string]any{"kind": "bed", "xCm": 300, "yCm": 300, "widthCm": 100, "heightCm": 100}, alice)
|
map[string]any{"kind": "bed", "xCm": 300, "yCm": 300, "widthCm": 100, "heightCm": 100}, alice)
|
||||||
oid := int64(decodeGarden(t, w.Body.Bytes())["id"].(float64))
|
oid := int64(decodeMap(t, w.Body.Bytes())["id"].(float64))
|
||||||
|
|
||||||
// Bob can't see the garden or its objects — all 404.
|
// Bob can't see the garden or its objects — all 404.
|
||||||
if w := doJSON(t, r, http.MethodGet, fullPath(gid), nil, bob); w.Code != http.StatusNotFound {
|
if w := doJSON(t, r, http.MethodGet, fullPath(gid), nil, bob); w.Code != http.StatusNotFound {
|
||||||
@@ -134,6 +134,42 @@ func TestObjectCrossUserIsNotFound(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestObjectPatchClearsColorAndProps(t *testing.T) {
|
||||||
|
r := authEngine(t, localCfg())
|
||||||
|
cookie := registerAndCookie(t, r, "[email protected]")
|
||||||
|
gid := createGardenAPI(t, r, cookie, "Yard")
|
||||||
|
|
||||||
|
// Create with a color override and props.
|
||||||
|
w := doJSON(t, r, http.MethodPost, objectsPath(gid),
|
||||||
|
map[string]any{"kind": "bed", "xCm": 300, "yCm": 300, "widthCm": 100, "heightCm": 100,
|
||||||
|
"color": "#3f8f4f", "props": map[string]any{"heightCm": 40}}, cookie)
|
||||||
|
obj := decodeMap(t, w.Body.Bytes())
|
||||||
|
oid := int64(obj["id"].(float64))
|
||||||
|
if obj["color"].(string) != "#3f8f4f" {
|
||||||
|
t.Fatalf("color not set on create: %v", obj["color"])
|
||||||
|
}
|
||||||
|
|
||||||
|
// PATCH color:null props:null clears both back to absent (omitempty).
|
||||||
|
w = doJSON(t, r, http.MethodPatch, objectPath(oid),
|
||||||
|
map[string]any{"color": nil, "props": nil, "version": 1}, cookie)
|
||||||
|
if w.Code != http.StatusOK {
|
||||||
|
t.Fatalf("clear patch: status %d, body %s", w.Code, w.Body.String())
|
||||||
|
}
|
||||||
|
cleared := decodeMap(t, w.Body.Bytes())
|
||||||
|
if _, present := cleared["color"]; present {
|
||||||
|
t.Errorf("color should be cleared (absent), got %v", cleared["color"])
|
||||||
|
}
|
||||||
|
if _, present := cleared["props"]; present {
|
||||||
|
t.Errorf("props should be cleared (absent), got %v", cleared["props"])
|
||||||
|
}
|
||||||
|
|
||||||
|
// A patch that omits color leaves it unchanged (still absent here).
|
||||||
|
w = doJSON(t, r, http.MethodPatch, objectPath(oid), map[string]any{"xCm": 350, "version": 2}, cookie)
|
||||||
|
if w.Code != http.StatusOK {
|
||||||
|
t.Fatalf("move patch: %d", w.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestObjectValidationRejects(t *testing.T) {
|
func TestObjectValidationRejects(t *testing.T) {
|
||||||
r := authEngine(t, localCfg())
|
r := authEngine(t, localCfg())
|
||||||
cookie := registerAndCookie(t, r, "[email protected]")
|
cookie := registerAndCookie(t, r, "[email protected]")
|
||||||
@@ -154,7 +190,7 @@ func TestObjectValidationRejects(t *testing.T) {
|
|||||||
if w.Code != http.StatusCreated {
|
if w.Code != http.StatusCreated {
|
||||||
t.Fatalf("props create = %d, body %s", w.Code, w.Body.String())
|
t.Fatalf("props create = %d, body %s", w.Code, w.Body.String())
|
||||||
}
|
}
|
||||||
if props, _ := decodeGarden(t, w.Body.Bytes())["props"].(string); props == "" {
|
if props, _ := decodeMap(t, w.Body.Bytes())["props"].(string); props == "" {
|
||||||
t.Error("props should be stored and returned as a JSON string")
|
t.Error("props should be stored and returned as a JSON string")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+41
-28
@@ -15,17 +15,17 @@ const (
|
|||||||
maxObjectPropsLen = 20_000
|
maxObjectPropsLen = 20_000
|
||||||
)
|
)
|
||||||
|
|
||||||
// objectKinds is the set of valid garden_objects.kind values.
|
// objectKinds maps each valid garden_objects.kind to its traits. plantable is
|
||||||
var objectKinds = map[string]bool{
|
// the default (beds/bags/containers/in-ground hold plants; trees/paths/
|
||||||
domain.KindBed: true, domain.KindGrowBag: true, domain.KindContainer: true,
|
// structures don't) and is overridable per object.
|
||||||
domain.KindInGround: true, domain.KindTree: true, domain.KindPath: true, domain.KindStructure: true,
|
var objectKinds = map[string]struct{ plantable bool }{
|
||||||
}
|
domain.KindBed: {plantable: true},
|
||||||
|
domain.KindGrowBag: {plantable: true},
|
||||||
// plantableByDefault: beds/bags/containers/in-ground hold plants; trees, paths,
|
domain.KindContainer: {plantable: true},
|
||||||
// and structures don't. Overridable per object.
|
domain.KindInGround: {plantable: true},
|
||||||
var plantableByDefault = map[string]bool{
|
domain.KindTree: {plantable: false},
|
||||||
domain.KindBed: true, domain.KindGrowBag: true, domain.KindContainer: true, domain.KindInGround: true,
|
domain.KindPath: {plantable: false},
|
||||||
domain.KindTree: false, domain.KindPath: false, domain.KindStructure: false,
|
domain.KindStructure: {plantable: false},
|
||||||
}
|
}
|
||||||
|
|
||||||
// ObjectInput is the payload for creating a garden object. Plantable nil means
|
// ObjectInput is the payload for creating a garden object. Plantable nil means
|
||||||
@@ -48,6 +48,10 @@ type ObjectInput struct {
|
|||||||
|
|
||||||
// ObjectPatch is a partial update: every field is optional (nil = leave as-is).
|
// ObjectPatch is a partial update: every field is optional (nil = leave as-is).
|
||||||
// Kind and shape are intentionally immutable after creation.
|
// Kind and shape are intentionally immutable after creation.
|
||||||
|
//
|
||||||
|
// Color and Props are nullable in the DB, so they use an explicit "set" flag to
|
||||||
|
// tell "clear to NULL" (Set*=true, value nil) apart from "leave unchanged"
|
||||||
|
// (Set*=false) — a plain nil pointer can't express both.
|
||||||
type ObjectPatch struct {
|
type ObjectPatch struct {
|
||||||
Name *string
|
Name *string
|
||||||
XCM *float64
|
XCM *float64
|
||||||
@@ -57,7 +61,9 @@ type ObjectPatch struct {
|
|||||||
RotationDeg *float64
|
RotationDeg *float64
|
||||||
ZIndex *int
|
ZIndex *int
|
||||||
Plantable *bool
|
Plantable *bool
|
||||||
|
SetColor bool
|
||||||
Color *string
|
Color *string
|
||||||
|
SetProps bool
|
||||||
Props *string
|
Props *string
|
||||||
Notes *string
|
Notes *string
|
||||||
}
|
}
|
||||||
@@ -79,14 +85,13 @@ func (s *Service) CreateObject(ctx context.Context, actorID, gardenID int64, in
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if !objectKinds[in.Kind] {
|
// finalizeObject is the single validation point (it rejects an unknown kind),
|
||||||
return nil, domain.ErrInvalidInput
|
// so an unknown kind here just yields plantable=false before being rejected.
|
||||||
}
|
|
||||||
shape := in.Shape
|
shape := in.Shape
|
||||||
if shape == "" {
|
if shape == "" {
|
||||||
shape = domain.ShapeRect
|
shape = domain.ShapeRect
|
||||||
}
|
}
|
||||||
plantable := plantableByDefault[in.Kind]
|
plantable := objectKinds[in.Kind].plantable
|
||||||
if in.Plantable != nil {
|
if in.Plantable != nil {
|
||||||
plantable = *in.Plantable
|
plantable = *in.Plantable
|
||||||
}
|
}
|
||||||
@@ -113,14 +118,25 @@ func (s *Service) CreateObject(ctx context.Context, actorID, gardenID int64, in
|
|||||||
return s.store.CreateObject(ctx, o)
|
return s.store.CreateObject(ctx, o)
|
||||||
|
gitea-actions
commented
⚪ UpdateObject and DeleteObject duplicate the same fetch-then-authorize sequence; could be factored into a shared helper maintainability · flagged by 1 model
🪰 Gadfly · advisory ⚪ **UpdateObject and DeleteObject duplicate the same fetch-then-authorize sequence; could be factored into a shared helper**
_maintainability · flagged by 1 model_
- `internal/service/objects.go:118-126` and `internal/service/objects.go:138-145` — `UpdateObject` and `DeleteObject` repeat the identical fetch-then-authorize sequence: ```go o, err := s.store.GetObject(ctx, objectID) if err != nil { return nil, err } g, err := s.requireGardenRole(ctx, actorID, o.GardenID, roleEditor) if err != nil { return nil, err } ``` A small helper (e.g. `requireObjectRole(ctx, actorID, objectID, min) (*domain.GardenObject, *domain.Garden, error)`) would remove the duplica…
<sub>🪰 Gadfly · advisory</sub>
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
// objectForRole loads an object and enforces that the actor holds at least min
|
||||||
|
// on its owning garden, returning both. A missing object — or one in a garden
|
||||||
|
// the actor can't see — is ErrNotFound (existence masked, same as gardens).
|
||||||
|
func (s *Service) objectForRole(ctx context.Context, actorID, objectID int64, min gardenRole) (*domain.GardenObject, *domain.Garden, error) {
|
||||||
|
o, err := s.store.GetObject(ctx, objectID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err // ErrNotFound
|
||||||
|
}
|
||||||
|
g, err := s.requireGardenRole(ctx, actorID, o.GardenID, min)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
return o, g, nil
|
||||||
|
}
|
||||||
|
|
||||||
// UpdateObject applies a partial, version-guarded patch to an object in a garden
|
// UpdateObject applies a partial, version-guarded patch to an object in a garden
|
||||||
// the actor can edit. On a version mismatch it returns (current, ErrVersionConflict).
|
// the actor can edit. On a version mismatch it returns (current, ErrVersionConflict).
|
||||||
func (s *Service) UpdateObject(ctx context.Context, actorID, objectID int64, patch ObjectPatch, version int64) (*domain.GardenObject, error) {
|
func (s *Service) UpdateObject(ctx context.Context, actorID, objectID int64, patch ObjectPatch, version int64) (*domain.GardenObject, error) {
|
||||||
o, err := s.store.GetObject(ctx, objectID)
|
o, g, err := s.objectForRole(ctx, actorID, objectID, roleEditor)
|
||||||
if err != nil {
|
|
||||||
return nil, err // ErrNotFound
|
|
||||||
}
|
|
||||||
g, err := s.requireGardenRole(ctx, actorID, o.GardenID, roleEditor)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -136,11 +152,7 @@ func (s *Service) UpdateObject(ctx context.Context, actorID, objectID int64, pat
|
|||||||
// DeleteObject removes an object (its plantings cascade) from a garden the actor
|
// DeleteObject removes an object (its plantings cascade) from a garden the actor
|
||||||
// can edit.
|
// can edit.
|
||||||
func (s *Service) DeleteObject(ctx context.Context, actorID, objectID int64) error {
|
func (s *Service) DeleteObject(ctx context.Context, actorID, objectID int64) error {
|
||||||
o, err := s.store.GetObject(ctx, objectID)
|
if _, _, err := s.objectForRole(ctx, actorID, objectID, roleEditor); err != nil {
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if _, err := s.requireGardenRole(ctx, actorID, o.GardenID, roleEditor); err != nil {
|
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
return s.store.DeleteObject(ctx, objectID)
|
return s.store.DeleteObject(ctx, objectID)
|
||||||
@@ -193,10 +205,11 @@ func applyObjectPatch(o *domain.GardenObject, p ObjectPatch) {
|
|||||||
if p.Plantable != nil {
|
if p.Plantable != nil {
|
||||||
o.Plantable = *p.Plantable
|
o.Plantable = *p.Plantable
|
||||||
}
|
}
|
||||||
if p.Color != nil {
|
// Color/Props: Set* distinguishes "clear to NULL" (value nil) from unchanged.
|
||||||
|
if p.SetColor {
|
||||||
o.Color = p.Color
|
o.Color = p.Color
|
||||||
}
|
}
|
||||||
if p.Props != nil {
|
if p.SetProps {
|
||||||
o.Props = p.Props
|
o.Props = p.Props
|
||||||
}
|
}
|
||||||
if p.Notes != nil {
|
if p.Notes != nil {
|
||||||
@@ -208,7 +221,7 @@ func applyObjectPatch(o *domain.GardenObject, p ObjectPatch) {
|
|||||||
// object against its garden. Shared by create and update so both enforce the
|
// object against its garden. Shared by create and update so both enforce the
|
||||||
|
gitea-actions
commented
🟡 validDimensionCM uses garden-named constants for object validation maintainability · flagged by 1 model
🪰 Gadfly · advisory 🟡 **validDimensionCM uses garden-named constants for object validation**
_maintainability · flagged by 1 model_
- `internal/service/objects.go:221` calls `validDimensionCM`, which lives in `gardens.go` and checks against constants named `minGardenCM`/`maxGardenCM`. Object dimensions happen to share the same 1 cm–100 m range, but the garden-specific naming hides this coupling: a future change to garden bounds would silently change object bounds too. **Fix:** either extract a generic `validDimensionCM` with neutral constants into a shared location, or give objects an explicit `validObjectDimensionCM` so the…
<sub>🪰 Gadfly · advisory</sub>
|
|||||||
// same invariants.
|
// same invariants.
|
||||||
func finalizeObject(o *domain.GardenObject, g *domain.Garden) error {
|
func finalizeObject(o *domain.GardenObject, g *domain.Garden) error {
|
||||||
if !objectKinds[o.Kind] {
|
if _, ok := objectKinds[o.Kind]; !ok {
|
||||||
return domain.ErrInvalidInput
|
return domain.ErrInvalidInput
|
||||||
}
|
}
|
||||||
// rect/circle only; polygon is reserved in the schema but not supported yet.
|
// rect/circle only; polygon is reserved in the schema but not supported yet.
|
||||||
|
|||||||
@@ -7,9 +7,11 @@ import (
|
|||||||
"gitea.stevedudenhoeffer.com/steve/pansy/internal/domain"
|
"gitea.stevedudenhoeffer.com/steve/pansy/internal/domain"
|
||||||
)
|
)
|
||||||
|
|
||||||
// scanPlanting reads a plantings row in table-declared column order (id,
|
// plantingColumns lists plantings columns in the order scanPlanting expects.
|
||||||
// object_id, plant_id, x_cm, y_cm, radius_cm, count, label, planted_at,
|
// Used unqualified for direct selects; the /full read below qualifies with pl.
|
||||||
// removed_at, version, created_at, updated_at) — the order SELECT pl.* yields.
|
const plantingColumns = `id, object_id, plant_id, x_cm, y_cm, radius_cm, count, label,
|
||||||
|
planted_at, removed_at, version, created_at, updated_at`
|
||||||
|
|
||||||
func scanPlanting(s scanner) (*domain.Planting, error) {
|
func scanPlanting(s scanner) (*domain.Planting, error) {
|
||||||
var p domain.Planting
|
var p domain.Planting
|
||||||
if err := s.Scan(
|
if err := s.Scan(
|
||||||
@@ -27,10 +29,8 @@ func scanPlanting(s scanner) (*domain.Planting, error) {
|
|||||||
// non-nil slice (empty until plantings CRUD lands in #14). Plop CRUD itself is
|
// non-nil slice (empty until plantings CRUD lands in #14). Plop CRUD itself is
|
||||||
// #14; this is only the /full read side.
|
// #14; this is only the /full read side.
|
||||||
func (d *DB) ListActivePlantingsForGarden(ctx context.Context, gardenID int64) ([]domain.Planting, error) {
|
func (d *DB) ListActivePlantingsForGarden(ctx context.Context, gardenID int64) ([]domain.Planting, error) {
|
||||||
// pl.* returns the plantings columns in table-declared order, which matches
|
|
||||||
// plantingColumns / scanPlanting.
|
|
||||||
rows, err := d.sql.QueryContext(ctx,
|
rows, err := d.sql.QueryContext(ctx,
|
||||||
`SELECT pl.* FROM plantings pl
|
`SELECT `+qualifyColumns("pl", plantingColumns)+` FROM plantings pl
|
||||||
JOIN garden_objects o ON o.id = pl.object_id
|
JOIN garden_objects o ON o.id = pl.object_id
|
||||||
WHERE o.garden_id = ? AND pl.removed_at IS NULL
|
WHERE o.garden_id = ? AND pl.removed_at IS NULL
|
||||||
ORDER BY pl.id`,
|
ORDER BY pl.id`,
|
||||||
|
gitea-actions
commented
🟡 SELECT pl. couples scanPlanting to table column order; prefer explicit column list when #14 extends the table* maintainability · flagged by 1 model
🪰 Gadfly · advisory 🟡 **SELECT pl.* couples scanPlanting to table column order; prefer explicit column list when #14 extends the table**
_maintainability · flagged by 1 model_
- **`internal/store/plantings.go:36` / `plants.go:34` — `SELECT pl.*` / `SELECT DISTINCT p.*` rely on table-declared column order.** This is acknowledged in comments, which is good, but it's a latent maintainability hazard: if a column is added/reordered in the `plantings`/`plants` schema later (e.g. in #12/#14), `scanPlanting`/`scanPlant` will silently break at runtime, not compile time. The `objects.go` path avoids this by listing `objectColumns` explicitly. Suggested fix: when #12/#14 extend…
<sub>🪰 Gadfly · advisory</sub>
|
|||||||
|
|||||||
@@ -7,9 +7,10 @@ import (
|
|||||||
"gitea.stevedudenhoeffer.com/steve/pansy/internal/domain"
|
"gitea.stevedudenhoeffer.com/steve/pansy/internal/domain"
|
||||||
)
|
)
|
||||||
|
|
||||||
// scanPlant reads a plants row in table-declared column order (id, owner_id,
|
// plantColumns lists plants columns in the order scanPlant expects.
|
||||||
// name, category, spacing_cm, color, icon, days_to_maturity, notes, version,
|
const plantColumns = `id, owner_id, name, category, spacing_cm, color, icon,
|
||||||
// created_at, updated_at) — the order SELECT p.* yields.
|
days_to_maturity, notes, version, created_at, updated_at`
|
||||||
|
|
||||||
func scanPlant(s scanner) (*domain.Plant, error) {
|
func scanPlant(s scanner) (*domain.Plant, error) {
|
||||||
var p domain.Plant
|
var p domain.Plant
|
||||||
if err := s.Scan(
|
if err := s.Scan(
|
||||||
@@ -26,9 +27,8 @@ func scanPlant(s scanner) (*domain.Plant, error) {
|
|||||||
// non-nil slice (empty until plantings exist, #14). Full plant CRUD/seeding is
|
// non-nil slice (empty until plantings exist, #14). Full plant CRUD/seeding is
|
||||||
// #12; this is only the /full read side.
|
// #12; this is only the /full read side.
|
||||||
func (d *DB) ListReferencedPlants(ctx context.Context, gardenID int64) ([]domain.Plant, error) {
|
func (d *DB) ListReferencedPlants(ctx context.Context, gardenID int64) ([]domain.Plant, error) {
|
||||||
// p.* returns the plants columns in table-declared order, matching scanPlant.
|
|
||||||
rows, err := d.sql.QueryContext(ctx,
|
rows, err := d.sql.QueryContext(ctx,
|
||||||
`SELECT DISTINCT p.* FROM plants p
|
`SELECT DISTINCT `+qualifyColumns("p", plantColumns)+` FROM plants p
|
||||||
JOIN plantings pl ON pl.plant_id = p.id
|
JOIN plantings pl ON pl.plant_id = p.id
|
||||||
JOIN garden_objects o ON o.id = pl.object_id
|
JOIN garden_objects o ON o.id = pl.object_id
|
||||||
WHERE o.garden_id = ? AND pl.removed_at IS NULL
|
WHERE o.garden_id = ? AND pl.removed_at IS NULL
|
||||||
|
|||||||
@@ -99,6 +99,17 @@ func pragmaName(p string) string {
|
|||||||
return strings.ToLower(strings.TrimSpace(p))
|
return strings.ToLower(strings.TrimSpace(p))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// qualifyColumns prefixes each comma-separated column in cols with "alias." so a
|
||||||
|
// shared column list can be used in a JOIN — e.g. qualifyColumns("pl", "id, x")
|
||||||
|
// → "pl.id, pl.x". Whitespace/newlines in the list are trimmed.
|
||||||
|
func qualifyColumns(alias, cols string) string {
|
||||||
|
parts := strings.Split(cols, ",")
|
||||||
|
for i, p := range parts {
|
||||||
|
parts[i] = alias + "." + strings.TrimSpace(p)
|
||||||
|
}
|
||||||
|
return strings.Join(parts, ", ")
|
||||||
|
}
|
||||||
|
|
||||||
// Close closes the underlying database.
|
// Close closes the underlying database.
|
||||||
func (d *DB) Close() error { return d.sql.Close() }
|
func (d *DB) Close() error { return d.sql.Close() }
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user
🟡 decodeGarden helper reused to decode object payloads; misleading name for non-garden responses
maintainability · flagged by 1 model
🪰 Gadfly · advisory