all repos — cameraman @ 347af7a085d07e23fe44d7a1366e71d8af37cece

handlers.go (view raw)

  1package main
  2
  3import (
  4	"errors"
  5	"fmt"
  6	"net/http"
  7	"time"
  8
  9	"github.com/gin-gonic/gin"
 10)
 11
 12func validateDate(month, day uint, year *uint) error {
 13	if month < 1 || month > 12 {
 14		return errors.New("invalid month: must be between 1 and 12")
 15	}
 16
 17	if day < 1 || day > 31 {
 18		return errors.New("invalid day: must be between 1 and 31")
 19	}
 20
 21	var testYear uint
 22	if year == nil {
 23		testYear = 2023
 24	} else {
 25		testYear = *year
 26	}
 27
 28	// Construct a date and use time package to validate
 29	dateStr := fmt.Sprintf("%04d-%02d-%02d", testYear, month, day)
 30	_, err := time.Parse("2006-01-02", dateStr)
 31	if err != nil {
 32		return errors.New("invalid day for the given month")
 33	}
 34
 35	return nil
 36}
 37
 38func updateOccurrence(c *gin.Context, input Occurrence) {
 39	var occurrence Occurrence
 40	if err := db.First(&occurrence, input.ID).Error; err != nil {
 41		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
 42		return
 43	}
 44
 45	// Update existing record with new values
 46	if input.Day != 0 || input.Month != 0 {
 47		if err := validateDate(input.Month, input.Day, input.Year); err != nil {
 48			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
 49			return
 50		}
 51		occurrence.Day = input.Day
 52		occurrence.Month = input.Month
 53		occurrence.Year = input.Year
 54	}
 55	if input.Name != "" {
 56		occurrence.Name = input.Name
 57	}
 58	if input.Description != "" {
 59		occurrence.Description = input.Description
 60	}
 61	occurrence.Notify = input.Notify
 62	occurrence.Notified = input.Notified
 63	db.Save(&occurrence)
 64	c.JSON(http.StatusOK, occurrence)
 65}
 66
 67func addOccurrence(c *gin.Context) {
 68	var input Occurrence
 69	if err := c.ShouldBindJSON(&input); err != nil {
 70		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
 71		return
 72	}
 73
 74	if input.ID != 0 {
 75		updateOccurrence(c, input)
 76		return
 77	}
 78
 79	if err := validateDate(input.Month, input.Day, input.Year); err != nil {
 80		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
 81		return
 82	}
 83
 84	db.Create(&input)
 85	c.JSON(http.StatusOK, input)
 86}
 87
 88func getOccurrences(c *gin.Context) {
 89	var occurrences []Occurrence
 90	db.Find(&occurrences)
 91	c.JSON(http.StatusOK, occurrences)
 92}
 93
 94func deleteOccurrence(c *gin.Context) {
 95	id := c.Param("id")
 96	var occurrence Occurrence
 97
 98	if err := db.First(&occurrence, id).Error; err != nil {
 99		c.JSON(http.StatusNotFound, gin.H{"error": "Occurrence not found"})
100		return
101	}
102
103	db.Delete(&occurrence)
104	c.JSON(http.StatusOK, gin.H{"message": "Occurrence deleted"})
105}