aboutsummaryrefslogtreecommitdiffstats
path: root/api/handlers/calendar.go
blob: e0ed27fb849c3f6022c02ab3b0f3d990aaf738d0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package handlers

import (
	"errors"
	"net/http"

	"github.com/LMBishop/confplanner/api/dto"
	"github.com/LMBishop/confplanner/pkg/calendar"
	"github.com/LMBishop/confplanner/pkg/session"
)

func GetCalendar(calendarService calendar.Service, baseURL string) http.HandlerFunc {
	// TODO create config service
	return dto.WrapResponseFunc(func(w http.ResponseWriter, r *http.Request) error {
		session := r.Context().Value("session").(*session.UserSession)

		cal, err := calendarService.GetCalendarForUser(session.UserID)
		if err != nil {
			if errors.Is(err, calendar.ErrCalendarNotFound) {
				return &dto.ErrorResponse{
					Code:    http.StatusNotFound,
					Message: "Calendar not found",
				}
			}

			return err
		}

		return &dto.OkResponse{
			Code: http.StatusOK,
			Data: &dto.GetCalendarResponse{
				ID:   cal.ID,
				Name: cal.Name,
				Key:  cal.Key,
				URL:  baseURL + "/api/calendar/ical?name=" + cal.Name + "&key=" + cal.Key,
			},
		}
	})
}

func CreateCalendar(calendarService calendar.Service, baseURL string) http.HandlerFunc {
	return dto.WrapResponseFunc(func(w http.ResponseWriter, r *http.Request) error {
		session := r.Context().Value("session").(*session.UserSession)

		cal, err := calendarService.CreateCalendarForUser(session.UserID)
		if err != nil {
			return err
		}

		return &dto.OkResponse{
			Code: http.StatusCreated,
			Data: &dto.CreateCalendarResponse{
				ID:   cal.ID,
				Name: cal.Name,
				Key:  cal.Key,
				URL:  baseURL + "/calendar/ical?name=" + cal.Name + "&key=" + cal.Key,
			},
		}
	})
}

func DeleteCalendar(calendarService calendar.Service) http.HandlerFunc {
	return dto.WrapResponseFunc(func(w http.ResponseWriter, r *http.Request) error {
		session := r.Context().Value("session").(*session.UserSession)

		err := calendarService.DeleteCalendarForUser(session.UserID)
		if err != nil {
			if errors.Is(err, calendar.ErrCalendarNotFound) {
				return &dto.ErrorResponse{
					Code:    http.StatusNotFound,
					Message: "Calendar not found",
				}
			}

			return err
		}

		return &dto.OkResponse{
			Code: http.StatusOK,
		}
	})
}