-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler_feeds.go
107 lines (90 loc) · 1.88 KB
/
handler_feeds.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package main
import (
"encoding/json"
"net/http"
"time"
"github.com/bsach64/blogAggregator/internal/database"
"github.com/google/uuid"
)
func (cfg *apiConfig) handleCreateFeed(w http.ResponseWriter, req *http.Request, user database.User) {
type paramaters struct {
Name string `json:"name"`
Url string `json:"url"`
}
decoder := json.NewDecoder(req.Body)
params := paramaters{}
err := decoder.Decode(¶ms)
if err != nil {
respondWithError(
w,
http.StatusBadRequest,
err.Error(),
)
return
}
feed := database.CreateFeedParams{
ID: uuid.New(),
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
UserID: user.ID,
Name: params.Name,
Url: params.Url,
}
feedEntry, err := cfg.DB.CreateFeed(req.Context(), feed)
if err != nil {
respondWithError(
w,
http.StatusInternalServerError,
err.Error(),
)
return
}
type responseStruct struct {
NewFeed Feed `json:"feed"`
NewFeedFollow FeedFollow `json:"feed_follow"`
}
FeedFollow := database.CreateFeedFollowParams{
ID: uuid.New(),
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
UserID: user.ID,
FeedID: feedEntry.ID,
}
NewFeedFollow, err := cfg.DB.CreateFeedFollow(req.Context(), FeedFollow)
if err != nil {
respondWithError(
w,
http.StatusInternalServerError,
err.Error(),
)
return
}
respondWithJSON(
w,
http.StatusCreated,
responseStruct{
feedFromDatabaseFeed(feedEntry),
feedfollowFromDatabaseFeedFollow(NewFeedFollow),
},
)
}
func (cfg *apiConfig) handleGetAllFeeds(w http.ResponseWriter, req *http.Request) {
feeds, err := cfg.DB.GetAllFeeds(req.Context())
if err != nil {
respondWithError(
w,
http.StatusInternalServerError,
err.Error(),
)
return
}
fs := make([]Feed, 0)
for _, f := range feeds {
fs = append(fs, feedFromDatabaseFeed(f))
}
respondWithJSON(
w,
http.StatusOK,
fs,
)
}