-
Notifications
You must be signed in to change notification settings - Fork 0
/
handleFeeds.go
91 lines (70 loc) · 2.45 KB
/
handleFeeds.go
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
83
84
85
86
87
88
89
90
91
package main
import (
"encoding/json"
"fmt"
"net/http"
"github.com/google/uuid"
)
func(s *APIServer) HandleCreateFeed(res http.ResponseWriter, req *http.Request, user *User) error {
var reqBody CreateFeedRequest
if err := json.NewDecoder(req.Body).Decode(&reqBody); err != nil {
return InvalidJSON()
}
feed, err := NewFeed(reqBody.Name, reqBody.Url, user.ID)
if err != nil {
return err
}
createdFeed, err := s.Store.CreateFeedToDb(feed)
if err != nil {
return NewAPIError(http.StatusBadRequest, err)
}
feedFollows := NewFeedFollow(createdFeed.UserID, createdFeed.ID)
createdFeedFollows, err := s.Store.CreateFeedFollows(feedFollows)
if err != nil {
return err
}
return writeJSON(res, http.StatusCreated, map[string]any{
"feed": createdFeed,
"feed_follow": createdFeedFollows,
})
}
func(s *APIServer) HandleGetFeeds(res http.ResponseWriter, req *http.Request) error {
feedsFromDb, err := s.Store.GetFeeds()
if err != nil {
return err
}
return writeJSON(res, http.StatusOK, feedsFromDb)
}
func(s *APIServer) HandleCreateFeedFollows(res http.ResponseWriter, req *http.Request, user *User) error {
var reqBody FeedFollowRequest
if err := json.NewDecoder(req.Body).Decode(&reqBody); err != nil {
return InvalidJSON()
}
feedFollowtoDb := NewFeedFollow(user.ID, reqBody.FeedID)
feedFollow, err := s.Store.CreateFeedFollows(feedFollowtoDb)
if err != nil {
return NewAPIError(http.StatusBadRequest, err)
}
return writeJSON(res, http.StatusCreated, feedFollow)
}
func(s *APIServer) HandleGetFeedFollows(res http.ResponseWriter, req *http.Request, user *User) error {
feeds, err := s.Store.GetFeedFollows(user.ID)
if err != nil {
return err
}
return writeJSON(res, http.StatusOK, feeds)
}
func(s *APIServer) HandleDeleteFeedFollows(res http.ResponseWriter, req *http.Request, user *User) error {
params := req.PathValue("feedFollowID")
id, err := uuid.Parse(params)
if err != nil {
return NewAPIError(http.StatusBadRequest, fmt.Errorf("invalid params"))
}
if err := s.Store.DeleteFeedFollows(id, user.ID); err != nil {
return NewAPIError(http.StatusBadRequest, err)
}
return writeJSON(res, http.StatusOK, map[string]any{
"statusCode": http.StatusOK,
"msg": "feed with feed follows id: " + params + " successfully unfollowed",
})
}