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 int) 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 // Construct a date and use time package to validate
22 dateStr := fmt.Sprintf("2023-%02d-%02d", month, day)
23 _, err := time.Parse("2006-01-02", dateStr)
24 if err != nil {
25 return errors.New("invalid day for the given month")
26 }
27
28 return nil
29}
30
31func updateOccurrence(c *gin.Context, input Occurrence) {
32 var occurrence Occurrence
33 if err := db.First(&occurrence, input.ID).Error; err != nil {
34 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
35 return
36 }
37
38 // Update existing record with new values
39 if input.Day != 0 || input.Month != 0 {
40 if err := validateDate(input.Month, input.Day); err != nil {
41 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
42 return
43 }
44 occurrence.Month = input.Month
45 occurrence.Day = input.Day
46 }
47 if input.Name != "" {
48 occurrence.Name = input.Name
49 }
50 if input.Description != "" {
51 occurrence.Description = input.Description
52 }
53 occurrence.Notify = input.Notify
54 occurrence.Notified = input.Notified
55 db.Save(&occurrence)
56 c.JSON(http.StatusOK, occurrence)
57}
58
59func addOccurrence(c *gin.Context) {
60 var input Occurrence
61 if err := c.ShouldBindJSON(&input); err != nil {
62 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
63 return
64 }
65
66 if input.ID != 0 {
67 updateOccurrence(c, input)
68 return
69 }
70
71 if err := validateDate(input.Month, input.Day); err != nil {
72 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
73 return
74 }
75
76 db.Create(&input)
77 c.JSON(http.StatusOK, input)
78}
79
80func getOccurrences(c *gin.Context) {
81 var occurrences []Occurrence
82 db.Find(&occurrences)
83 c.JSON(http.StatusOK, occurrences)
84}
85
86func deleteOccurrence(c *gin.Context) {
87 id := c.Param("id")
88 var occurrence Occurrence
89
90 if err := db.First(&occurrence, id).Error; err != nil {
91 c.JSON(http.StatusNotFound, gin.H{"error": "Occurrence not found"})
92 return
93 }
94
95 db.Delete(&occurrence)
96 c.JSON(http.StatusOK, gin.H{"message": "Occurrence deleted"})
97}