Skip to content

Commit

Permalink
vingo: fix days endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
hannes-dev committed Aug 5, 2024
1 parent 7ecab8d commit 87d0c00
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 31 deletions.
53 changes: 22 additions & 31 deletions vingo/database/days.go
Original file line number Diff line number Diff line change
@@ -1,52 +1,43 @@
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
}

return nil
}

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
}
Expand Down
10 changes: 10 additions & 0 deletions vingo/handlers/days.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
1 change: 1 addition & 0 deletions vingo/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down

0 comments on commit 87d0c00

Please sign in to comment.