all repos — cameraman @ f55f9235f8e44c905a07eafb77b9dd63b41f403d

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 addOccurrence(c *gin.Context) {
32	var input Occurrence
33	if err := c.ShouldBindJSON(&input); err != nil {
34		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
35		return
36	}
37
38	// Validate date
39	if err := validateDate(input.Month, input.Day); err != nil {
40		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
41		return
42	}
43
44	var occurrence Occurrence
45	if input.ID != 0 {
46		if err := db.First(&occurrence, input.ID).Error; err == nil {
47			// Update existing record with new values
48			if input.Month != 0 {
49				occurrence.Month = input.Month
50			}
51			if input.Day != 0 {
52				occurrence.Day = input.Day
53			}
54			if input.Name != "" {
55				occurrence.Name = input.Name
56			}
57			if input.Description != "" {
58				occurrence.Description = input.Description
59			}
60			occurrence.Notify = input.Notify
61			db.Save(&occurrence)
62			c.JSON(http.StatusOK, occurrence)
63			return
64		}
65	}
66
67	// Create a new record if no existing record is found
68	occurrence = input
69	db.Create(&occurrence)
70	c.JSON(http.StatusOK, occurrence)
71}
72
73func getOccurrences(c *gin.Context) {
74	var occurrences []Occurrence
75	db.Find(&occurrences)
76	c.JSON(http.StatusOK, occurrences)
77}
78
79func deleteOccurrence(c *gin.Context) {
80	id := c.Param("id")
81	var occurrence Occurrence
82
83	if err := db.First(&occurrence, id).Error; err != nil {
84		c.JSON(http.StatusNotFound, gin.H{"error": "Occurrence not found"})
85		return
86	}
87
88	db.Delete(&occurrence)
89	c.JSON(http.StatusOK, gin.H{"message": "Occurrence deleted"})
90}