-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler_chirps_get.go
77 lines (65 loc) · 1.67 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
package main
import (
"net/http"
"sort"
"strconv"
"github.com/go-chi/chi/v5"
)
func (cfg *apiConfig) handlerChirpsRetrieve(w http.ResponseWriter, r *http.Request) {
dbChirps, err := cfg.DB.GetChirps()
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Couldn't retrieve chirps")
return
}
authorID := r.URL.Query().Get("author_id")
sortOrder := r.URL.Query().Get("sort")
chirps := []Chirp{}
if authorID != "" {
intAuthorID, _ := strconv.Atoi(authorID)
for _, dbChirp := range dbChirps {
if dbChirp.AuthorID == intAuthorID {
chirps = append(chirps, Chirp{
ID: dbChirp.ID,
Body: dbChirp.Body,
AuthorID: dbChirp.AuthorID,
})
}
}
} else {
for _, dbChirp := range dbChirps {
chirps = append(chirps, Chirp{
ID: dbChirp.ID,
Body: dbChirp.Body,
AuthorID: dbChirp.AuthorID,
})
}
}
if sortOrder == "desc" {
sort.Slice(chirps, func(i, j int) bool {
return chirps[i].ID > chirps[j].ID
})
} else {
sort.Slice(chirps, func(i, j int) bool {
return chirps[i].ID < chirps[j].ID
})
}
respondWithJSON(w, http.StatusOK, chirps)
}
func (cfg *apiConfig) handlerChirpsGet(w http.ResponseWriter, r *http.Request) {
chirpIDString := chi.URLParam(r, "chirpID")
chirpID, err := strconv.Atoi(chirpIDString)
if err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid Chirp ID")
return
}
dbChirp, err := cfg.DB.GetChirpID(chirpID)
if err != nil {
respondWithError(w, http.StatusNotFound, "Couldn't get chirp")
return
}
respondWithJSON(w, http.StatusOK, Chirp{
ID: dbChirp.ID,
Body: dbChirp.Body,
AuthorID: dbChirp.AuthorID,
})
}