fix: more refactoring #181

This commit is contained in:
2024-10-20 15:02:39 +02:00
parent 38d530a3c9
commit 77bf66a4fc
6 changed files with 153 additions and 56 deletions

View File

@@ -5,13 +5,20 @@ import (
"me-fit/utils"
"database/sql"
"errors"
"time"
"github.com/google/uuid"
)
var (
ErrWorkoutNotExists = errors.New("Workout does not exist")
)
type DbWorkout interface {
InsertWorkout(userId uuid.UUID, workout *WorkoutInsert) (*Workout, error)
GetWorkouts(userId uuid.UUID) ([]Workout, error)
DeleteWorkout(userId uuid.UUID, rowId int) error
}
type DbWorkoutSqlite struct {
@@ -58,3 +65,46 @@ func (db DbWorkoutSqlite) InsertWorkout(userId uuid.UUID, workout *WorkoutInsert
return NewWorkoutFromInsert(rowId, workout), nil
}
func (db DbWorkoutSqlite) GetWorkouts(userId uuid.UUID) ([]Workout, error) {
rows, err := db.db.Query("SELECT rowid, date, type, sets, reps FROM workout WHERE user_id = ? ORDER BY date desc", userId)
if err != nil {
utils.LogError("Could not get workouts", err)
return nil, types.ErrInternal
}
var workouts = make([]Workout, 0)
for rows.Next() {
var workout Workout
err = rows.Scan(&workout.RowId, &workout.Date, &workout.Type, &workout.Sets, &workout.Reps)
if err != nil {
utils.LogError("Could not scan workout", err)
return nil, types.ErrInternal
}
workouts = append(workouts, workout)
}
return workouts, nil
}
func (db DbWorkoutSqlite) DeleteWorkout(userId uuid.UUID, rowId int) error {
res, err := db.db.Exec("DELETE FROM workout WHERE user_id = ? AND rowid = ?", userId, rowId)
if err != nil {
return types.ErrInternal
}
rows, err := res.RowsAffected()
if err != nil {
return types.ErrInternal
}
if rows == 0 {
return ErrWorkoutNotExists
}
return nil
}