Add food update
This commit is contained in:
@@ -11,7 +11,7 @@ type (
|
||||
db *DB
|
||||
}
|
||||
Food struct {
|
||||
rowid int
|
||||
rowid int64
|
||||
date string
|
||||
food string
|
||||
descripton string
|
||||
@@ -92,6 +92,35 @@ func (s *FoodService) Create(food Food) (Food, error) {
|
||||
return s.GetByRowid(rowid)
|
||||
}
|
||||
|
||||
func (s *FoodService) Update(food Food) (Food, error) {
|
||||
if s.db == nil || !s.db.Ready {
|
||||
return food, fmt.Errorf("cannot update food, db is nil or is not ready")
|
||||
}
|
||||
if food.rowid <= 0 {
|
||||
return food, fmt.Errorf("cannot update food, rowid is less than or equal to 0")
|
||||
}
|
||||
if food.food == "" {
|
||||
return food, fmt.Errorf("cannot update food, food is empty")
|
||||
}
|
||||
if food.amount <= 0 {
|
||||
return food, fmt.Errorf("cannot update food, amount is less than or equal to 0")
|
||||
}
|
||||
|
||||
if food.per100 > 0 {
|
||||
_, err := s.db.writeConn.Exec("UPDATE food SET food = ?, description = ?, amount = ?, per100 = ? WHERE rowid = ?", food.food, food.descripton, food.amount, food.per100, food.rowid)
|
||||
if err != nil {
|
||||
return food, fmt.Errorf("error updating food: %v", err)
|
||||
}
|
||||
} else {
|
||||
_, err := s.db.writeConn.Exec("UPDATE food SET food = ?, description = ?, amount = ? WHERE rowid = ?", food.food, food.descripton, food.amount, food.rowid)
|
||||
if err != nil {
|
||||
return food, fmt.Errorf("error updating food: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
return s.GetByRowid(food.rowid)
|
||||
}
|
||||
|
||||
func (s *FoodService) GetByRowid(rowid int64) (Food, error) {
|
||||
var res Food
|
||||
if s.db == nil || !s.db.Ready {
|
||||
|
17
main.go
17
main.go
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"math/rand"
|
||||
"os"
|
||||
"sync"
|
||||
|
||||
@@ -70,12 +71,24 @@ func main() {
|
||||
// }
|
||||
// log.Println(food)
|
||||
|
||||
daily, err := foodService.GetDaily()
|
||||
// daily, err := foodService.GetDaily()
|
||||
// if err != nil {
|
||||
// Error.Printf("%++v", err)
|
||||
// os.Exit(1)
|
||||
// }
|
||||
// log.Println(daily)
|
||||
|
||||
test := Food{
|
||||
food: "test",
|
||||
amount: rand.Float32(),
|
||||
rowid: 766,
|
||||
}
|
||||
food, err := foodService.Update(test)
|
||||
if err != nil {
|
||||
Error.Printf("%++v", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
log.Println(daily)
|
||||
log.Println(food)
|
||||
|
||||
log.Println("done")
|
||||
wg.Wait()
|
||||
|
Reference in New Issue
Block a user