diff --git a/vingo/database/days.go b/vingo/database/days.go index c2b5e02..73daecc 100644 --- a/vingo/database/days.go +++ b/vingo/database/days.go @@ -1,28 +1,28 @@ package database -import "time" +import ( + "time" -func CreateDays(first_day time.Time, last_day time.Time) error { - tx, err := db.Begin() - if err != nil { - return err - } + "gorm.io/gorm" +) - defer tx.Rollback() - - for d := first_day; !d.After(last_day); d = d.AddDate(0, 0, 1) { - // Ignore weekends - if d.Weekday() == time.Saturday || d.Weekday() == time.Sunday { - continue +func CreateDays(first_day time.Time, last_day time.Time) error { + err := gorm_db.Transaction(func(tx *gorm.DB) error { + for d := first_day; !d.After(last_day); d = d.AddDate(0, 0, 1) { + // Ignore weekends + if d.Weekday() == time.Saturday || d.Weekday() == time.Sunday { + continue + } + + if err := tx.Create(&StreakDay{Date: d}).Error; err != nil { + return err + } } - _, err := db.Exec("INSERT INTO days (date) VALUES ($1);", d) - if err != nil { - return err - } - } + return nil + }) - if err = tx.Commit(); err != nil { + if err != nil { return err } @@ -30,23 +30,14 @@ func CreateDays(first_day time.Time, last_day time.Time) error { } func GetDays() ([]StreakDay, error) { - rows, err := db.Query("SELECT id, date FROM days ORDER BY date;") - if err != nil { - return nil, err - } - - days := make([]StreakDay, 0) - for rows.Next() { - var day StreakDay - rows.Scan(&day.Id, &day.Date) - days = append(days, day) - } + var days []StreakDay + err := gorm_db.Find(&days).Error - return days, nil + return days, err } func DeleteDay(dayId string) error { - _, err := db.Exec("DELETE FROM days WHERE id = $1;", dayId) + _, err := db.Exec("DELETE FROM streak_days WHERE id = $1;", dayId) if err != nil { return err } diff --git a/vingo/handlers/days.go b/vingo/handlers/days.go index 25dcdb6..d0b8a8b 100644 --- a/vingo/handlers/days.go +++ b/vingo/handlers/days.go @@ -40,3 +40,13 @@ func (Days) Delete(c *fiber.Ctx) error { return c.SendStatus(200) } + +func (Days) All(c *fiber.Ctx) error { + days, err := database.GetDays() + if err != nil { + logger.Println("Error getting days:", err) + return c.Status(500).SendString("Error getting days") + } + + return c.JSON(days) +} diff --git a/vingo/main.go b/vingo/main.go index d56e6de..8a6405c 100644 --- a/vingo/main.go +++ b/vingo/main.go @@ -56,6 +56,7 @@ func main() { admin := api.Group("/admin", handlers.IsAdmin) { + admin.Get("/days", handlers.Days{}.All) admin.Post("/days", handlers.Days{}.CreateMultiple) admin.Delete("/days/:id", handlers.Days{}.Delete) }