-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandle_chirps_get.go
More file actions
77 lines (64 loc) · 1.63 KB
/
handle_chirps_get.go
File metadata and controls
77 lines (64 loc) · 1.63 KB
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) handlerChirpsGet(w http.ResponseWriter, r *http.Request) {
dbChirps, err := cfg.DB.GetChirps()
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Could not retrieve chirps")
return
}
authorId := -1
authorIdString := r.URL.Query().Get("author_id")
if authorIdString != "" {
authorId, err = strconv.Atoi(authorIdString)
if err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid author ID")
return
}
}
sortDirection := "asc"
sortDirectionParam := r.URL.Query().Get("sort")
if sortDirectionParam == "desc" {
sortDirection = "desc"
}
chirps := []Chirp{}
for _, dbChirp := range dbChirps {
if authorId != -1 && dbChirp.AuthorID != authorId {
continue
}
chirps = append(chirps, Chirp{
ID: dbChirp.ID,
AuthorID: dbChirp.AuthorID,
Body: dbChirp.Body,
})
}
sort.Slice(chirps, func(i, j int) bool {
if sortDirection == "desc" {
return chirps[i].ID > chirps[j].ID
}
return chirps[i].ID < chirps[j].ID
})
respondWithJSON(w, http.StatusOK, chirps)
}
func (cfg *apiConfig) handlerChirpsGetById(w http.ResponseWriter, r *http.Request) {
chirpIdStr := chi.URLParam(r, "id")
chirpId, err := strconv.Atoi(chirpIdStr)
if err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid chirp id")
return
}
chirp, err := cfg.DB.GetChirp(chirpId)
if err != nil {
respondWithError(w, http.StatusNotFound, "Chirp not found")
return
}
respondWithJSON(w, http.StatusOK, Chirp{
ID: chirp.ID,
AuthorID: chirp.AuthorID,
Body: chirp.Body,
})
}