summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorxengineering <me@xengineering.eu>2024-05-15 20:18:39 +0200
committerxengineering <me@xengineering.eu>2024-05-17 23:20:41 +0200
commitbc149ee58122effc9d4c035da2af3a7ec1f2f862 (patch)
treeca58dac0b34ad771ef0821a2de887171d985d94d
parentf8f5d296f218f79646a54d3aed8d54fa9f8704c1 (diff)
downloadceres-bc149ee58122effc9d4c035da2af3a7ec1f2f862.tar
ceres-bc149ee58122effc9d4c035da2af3a7ec1f2f862.tar.zst
ceres-bc149ee58122effc9d4c035da2af3a7ec1f2f862.zip
model: Add strict Ingredient.Validate()
-rw-r--r--model/ingredient.go42
-rw-r--r--model/validation.go13
2 files changed, 54 insertions, 1 deletions
diff --git a/model/ingredient.go b/model/ingredient.go
index 85a4729..9922060 100644
--- a/model/ingredient.go
+++ b/model/ingredient.go
@@ -15,11 +15,46 @@ type Ingredient struct {
Step string `json:"step"`
}
+func (i *Ingredient) Validate() error {
+ var err error
+
+ if i.Id != "" {
+ err = isPositiveOrZeroInt(i.Id)
+ if err != nil {
+ return fmt.Errorf("Invalid ingredient ID: %w", err)
+ }
+ }
+
+ err = isPositiveOrZeroInt(i.Index)
+ if err != nil {
+ return fmt.Errorf("Invalid ingredient index: %w", err)
+ }
+
+ if i.Amount != "" {
+ err = isPositiveOrZeroFloat(i.Amount)
+ if err != nil {
+ return fmt.Errorf("Invalid ingredient amount: %w", err)
+ }
+ }
+
+ err = isPositiveOrZeroInt(i.Step)
+ if err != nil {
+ return fmt.Errorf("Ingredient does not reference a valid step ID: %w", err)
+ }
+
+ return nil
+}
+
func (i *Ingredient) Create(tx *sql.Tx) error {
if i.Id != "" {
return fmt.Errorf("Cannot create ingredient if ID is given")
}
+ err := i.Validate()
+ if err != nil {
+ return err
+ }
+
cmd := `
INSERT INTO ingredients
('index', amount, unit, 'type', step)
@@ -67,10 +102,15 @@ WHERE
return err
}
- return nil
+ return i.Validate()
}
func (i *Ingredient) Update(tx *sql.Tx) error {
+ err := i.Validate()
+ if err != nil {
+ return err
+ }
+
cmd := `
UPDATE
ingredients
diff --git a/model/validation.go b/model/validation.go
index d49141d..ac38777 100644
--- a/model/validation.go
+++ b/model/validation.go
@@ -26,3 +26,16 @@ func isPositiveOrZeroInt(s string) error {
return nil
}
+
+func isPositiveOrZeroFloat(s string) error {
+ f, err := strconv.ParseFloat(s, 32)
+ if err != nil {
+ return fmt.Errorf("'%s' cannot be casted to floating point number", s)
+ }
+
+ if f < 0 {
+ return fmt.Errorf("'%s' is negative", s)
+ }
+
+ return nil
+}