diff options
author | xengineering <me@xengineering.eu> | 2024-05-15 20:18:39 +0200 |
---|---|---|
committer | xengineering <me@xengineering.eu> | 2024-05-17 23:20:41 +0200 |
commit | bc149ee58122effc9d4c035da2af3a7ec1f2f862 (patch) | |
tree | ca58dac0b34ad771ef0821a2de887171d985d94d /model/ingredient.go | |
parent | f8f5d296f218f79646a54d3aed8d54fa9f8704c1 (diff) | |
download | ceres-bc149ee58122effc9d4c035da2af3a7ec1f2f862.tar ceres-bc149ee58122effc9d4c035da2af3a7ec1f2f862.tar.zst ceres-bc149ee58122effc9d4c035da2af3a7ec1f2f862.zip |
model: Add strict Ingredient.Validate()
Diffstat (limited to 'model/ingredient.go')
-rw-r--r-- | model/ingredient.go | 42 |
1 files changed, 41 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 |