From ae771a44c2ffe31dc1bd67a12b65849f7d7d2d11 Mon Sep 17 00:00:00 2001
From: xengineering <me@xengineering.eu>
Date: Wed, 15 May 2024 20:09:35 +0200
Subject: model: Make Recipe.Validate() more strict

Before the next release this method should be as strict as possible to
avoid cases where actually invalid enters databases.
---
 model/recipe.go | 37 +++++++++++++++++++++++++++++++++++++
 1 file changed, 37 insertions(+)

diff --git a/model/recipe.go b/model/recipe.go
index 7aebad4..4594287 100644
--- a/model/recipe.go
+++ b/model/recipe.go
@@ -5,6 +5,7 @@ import (
 	"encoding/json"
 	"errors"
 	"fmt"
+	"strconv"
 )
 
 type Recipe struct {
@@ -24,10 +25,46 @@ func (r Recipe) String() string {
 }
 
 func (r *Recipe) Validate() error {
+	if r.Id != "" {
+		id, err := strconv.Atoi(r.Id)
+		if err != nil {
+			return fmt.Errorf("Recipe has non-empty ID which is no integer: %w", err)
+		}
+
+		if id < 0 {
+			return fmt.Errorf("Recipes has negative ID: %d", id)
+		}
+	}
+
 	if r.Title == "" {
 		return fmt.Errorf("Recipes must have a title")
 	}
 
+	if r.Portions != "" {
+		portions, err := strconv.Atoi(r.Portions)
+		if err != nil {
+			return fmt.Errorf("Recipe has non-empty portions which is no integer: %w", err)
+		}
+
+		if portions < 0 {
+			return fmt.Errorf("Recipes has negative number of portions: %d", portions)
+		}
+	}
+
+	if r.Created != "" {
+		_, err := strconv.Atoi(r.Created)
+		if err != nil {
+			return fmt.Errorf("Recipe has non-empty time stamp 'created' which is no integer: %w", err)
+		}
+	}
+
+	if r.LastChanged != "" {
+		_, err := strconv.Atoi(r.LastChanged)
+		if err != nil {
+			return fmt.Errorf("Recipe has non-empty time stamp 'last_changed' which is no integer: %w", err)
+		}
+	}
+
 	return nil
 }
 
-- 
cgit v1.2.3-70-g09d2