Implement basic food service

This commit is contained in:
2024-08-09 16:21:11 +02:00
parent b265a06ce7
commit a23ada9bb0
4 changed files with 305 additions and 18 deletions

View File

@@ -1,5 +1,104 @@
package main
type FoodService struct {
db *DB
import (
"database/sql"
"fmt"
"log"
)
type (
FoodService struct {
db *DB
}
Food struct {
rowid int
date string
food string
descripton string
amount float32
per100 float32
energy float32
}
AggregatedFood struct {
period string
amount float32
avgPer100 float32
energy float32
}
)
const foodColumns = "rowid, date, food, description, amount, per100, energy"
const foodAggregatedColumns = "period, amount, avgPer100, energy"
func (s *FoodService) GetRecent() ([]Food, error) {
var res []Food
if s.db == nil || !s.db.Ready {
return res, fmt.Errorf("cannot get recent food, db is nil or is not ready")
}
row, _ := s.db.readConn.Query(fmt.Sprintf("SELECT %s from foodView WHERE date > datetime('now', '-%s days')", foodColumns, Settings.FoodDaysLookback))
var rows []Food
for row.Next() {
var food Food
err := row.Scan(&food.rowid, &food.date, &food.food, &food.descripton, &food.amount, &food.per100, &food.energy)
if err != nil {
log.Printf("error scanning row: %v", err)
continue
}
rows = append(rows, food)
}
log.Printf("%++v", rows)
return res, nil
}
func (s *FoodService) Create(food Food) (Food, error) {
if s.db == nil || !s.db.Ready {
return food, fmt.Errorf("cannot create food, db is nil or is not ready")
}
if food.food == "" {
return food, fmt.Errorf("cannot create food, food is empty")
}
if food.amount <= 0 {
return food, fmt.Errorf("cannot create food, amount is less than or equal to 0")
}
var res sql.Result
var err error
if food.per100 > 0 {
res, err = s.db.writeConn.Exec("INSERT INTO food (food, description, amount, per100) VALUES (?, ?, ?, ?)", food.food, food.descripton, food.amount, food.per100)
if err != nil {
return food, fmt.Errorf("error inserting food: %v", err)
}
} else {
res, err = s.db.writeConn.Exec("INSERT INTO food (food, description, amount) VALUES (?, ?, ?)", food.food, food.descripton, food.amount)
if err != nil {
return food, fmt.Errorf("error inserting food: %v", err)
}
}
rowid, err := res.LastInsertId()
if err != nil {
return food, fmt.Errorf("error getting last insert id: %v", err)
}
return s.GetByRowid(rowid)
}
func (s *FoodService) GetByRowid(rowid int64) (Food, error) {
var res Food
if s.db == nil || !s.db.Ready {
return res, fmt.Errorf("cannot get food by rowid, db is nil or is not ready")
}
row := s.db.readConn.QueryRow(fmt.Sprintf("SELECT %s from foodView WHERE rowid = ?", foodColumns), rowid)
err := row.Scan(&res.rowid, &res.date, &res.food, &res.descripton, &res.amount, &res.per100, &res.energy)
if err != nil {
return res, fmt.Errorf("error scanning row: %v", err)
}
return res, nil
}