-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler_chirps_get.go
78 lines (67 loc) · 1.85 KB
/
handler_chirps_get.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
package main
import (
"net/http"
"sort"
"github.com/google/uuid"
)
func (cfg *apiConfig) handlerChirpsGet(w http.ResponseWriter, r *http.Request) {
chirpIDString := r.PathValue("chirpID")
chirpID, err := uuid.Parse(chirpIDString)
if err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid chirp ID", err)
return
}
dbChirp, err := cfg.db.GetChirp(r.Context(), chirpID)
if err != nil {
respondWithError(w, http.StatusNotFound, "Couldn't get chirp", err)
return
}
respondWithJSON(w, http.StatusOK, Chirp{
ID: dbChirp.ID,
CreatedAt: dbChirp.CreatedAt,
UpdatedAt: dbChirp.UpdatedAt,
UserID: dbChirp.UserID,
Body: dbChirp.Body,
})
}
func (cfg *apiConfig) handlerChirpsRetrieve(w http.ResponseWriter, r *http.Request) {
dbChirps, err := cfg.db.GetChirps(r.Context())
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Couldn't retrieve chirps", err)
return
}
authorID := uuid.Nil
authorIDString := r.URL.Query().Get("author_id")
if authorIDString != "" {
authorID, err = uuid.Parse(authorIDString)
if err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid author ID", err)
return
}
}
sortDirection := "asc"
sortDirectionParam := r.URL.Query().Get("sort")
if sortDirectionParam == "desc" {
sortDirection = "desc"
}
chirps := []Chirp{}
for _, dbChirp := range dbChirps {
if authorID != uuid.Nil && dbChirp.UserID != authorID {
continue
}
chirps = append(chirps, Chirp{
ID: dbChirp.ID,
CreatedAt: dbChirp.CreatedAt,
UpdatedAt: dbChirp.UpdatedAt,
UserID: dbChirp.UserID,
Body: dbChirp.Body,
})
}
sort.Slice(chirps, func(i, j int) bool {
if sortDirection == "desc" {
return chirps[i].CreatedAt.After(chirps[j].CreatedAt)
}
return chirps[i].CreatedAt.Before(chirps[j].CreatedAt)
})
respondWithJSON(w, http.StatusOK, chirps)
}