From f8f5d296f218f79646a54d3aed8d54fa9f8704c1 Mon Sep 17 00:00:00 2001 From: xengineering Date: Wed, 15 May 2024 20:18:13 +0200 Subject: model: Add strict Step.Validate() --- model/step.go | 41 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/model/step.go b/model/step.go index e3fa24b..89a9efd 100644 --- a/model/step.go +++ b/model/step.go @@ -20,11 +20,45 @@ func (s Step) String() string { return string(b) } +func (s *Step) Validate() error { + var err error + + if s.Id != "" { + err = isPositiveOrZeroInt(s.Id) + if err != nil { + return fmt.Errorf("Invalid step ID: %w", err) + } + } + + if s.Index != "" { + err = isPositiveOrZeroInt(s.Index) + if err != nil { + return fmt.Errorf("Invalid step index: %w", err) + } + } + + if s.Text == "" { + return fmt.Errorf("Step text must not be empty") + } + + err = isPositiveOrZeroInt(s.Recipe) + if err != nil { + return fmt.Errorf("Step does not reference a valid recipe ID: %w", err) + } + + return nil +} + func (s *Step) Create(tx *sql.Tx) error { if s.Id != "" { return fmt.Errorf("Cannot create step if ID is given") } + err := s.Validate() + if err != nil { + return err + } + cmd := ` INSERT INTO steps ('index', text, recipe) @@ -127,10 +161,15 @@ WHERE } } - return nil + return s.Validate() } func (s *Step) Update(tx *sql.Tx) error { + err := s.Validate() + if err != nil { + return err + } + oldIngredients, err := s.getIngredientIds(tx) if err != nil { return err -- cgit v1.2.3-70-g09d2