summaryrefslogtreecommitdiff
path: root/model/ingredient.go
diff options
context:
space:
mode:
Diffstat (limited to 'model/ingredient.go')
-rw-r--r--model/ingredient.go42
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