import { db } from '$lib/database' import type { Err } from '$lib/types' export type Food = { rowid?: number, date?: Date, food: string, description?: string, amount: number, per100?: number, energy?: number, } const columns = ['rowid', 'date', 'food', 'description', 'amount', 'per100', 'energy'] const aggColumns = ['date', 'amount', 'avgPer100', 'energy'] const FoodService = { async GetAll() { return await db.select(` select ${columns.join(', ')} from food order by date desc `) }, async GetAllForDate(date: Date) { return await db.select(` select ${columns.join(', ')} from food where strftime('%Y-%m-%d', date) = strftime('%Y-%m-%d', '2024-06-12') or strftime('%Y-%m-%d', date) = strftime('%Y-%m-%d', date('2024-06-12', '-1 day')) order by date DESC; `, [date]) }, async Create(food: Food): Promise<[Food[], Err]> { if (!food.food) return [[food], 'food.food is required'] if (!food.amount) throw [[food], 'food.amount is required'] const res = await db.execute(`insert into food (food, description, amount) values ($1, $2, $3)`, [food.food, food.description, food.amount]) const row = await db.select(`select ${columns.join(', ')} from food where rowid = $1`, [res.lastInsertId]) return [row, null] }, async GetDaily(): Promise<[Food[], Err]> { const rows = await db.select(`select ${aggColumns.join(', ')} from daily limit 100`) return [rows, null] }, async GetWeekly(): Promise<[Food[], Err]> { const rows = await db.select(`select ${aggColumns.join(', ')} from weekly limit 100`) return [rows, null] }, async GetMonthly(): Promise<[Food[], Err]> { const rows = await db.select(`select ${aggColumns.join(', ')} from monthly limit 100`) return [rows, null] }, async GetYearly(): Promise<[Food[], Err]> { const rows = await db.select(`select ${aggColumns.join(', ')} from yearly limit 100`) return [rows, null] }, } export { FoodService }