-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler_chirps_get.go
More file actions
67 lines (47 loc) · 1.35 KB
/
handler_chirps_get.go
File metadata and controls
67 lines (47 loc) · 1.35 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
package main
import (
"net/http"
"sort"
"github.com/google/uuid"
)
func (cfg *apiConfig) handlerChirpsRetrieve(w http.ResponseWriter, r *http.Request ){
authorIDString := r.URL.Query().Get("author_id")
sortDirection := r.URL.Query().Get("sort")
if sortDirection!="" && (sortDirection!="asc" && sortDirection!="desc"){
respondWithError(w, http.StatusBadRequest, "Invalid sort order", nil)
return
}
dbchirps, err:= cfg.dbQueries.GetAllChirps(r.Context())
if err!=nil{
respondWithError(w, http.StatusInternalServerError, err.Error(), err)
return
}
if authorIDString!=""{
authorID, err := uuid.Parse(authorIDString)
if err!=nil{
respondWithError(w, http.StatusBadRequest, "Invalid user ID", err)
return
}
dbchirps, err = cfg.dbQueries.GetChirpByUserID(r.Context(), authorID)
if err!=nil{
respondWithError(w, http.StatusInternalServerError, err.Error(), err)
return
}
}
if sortDirection == "desc" {
sort.Slice(dbchirps, func(i, j int) bool {
return dbchirps[i].CreatedAt.After(dbchirps[j].CreatedAt)
})
}
chirps :=[]Chirp{}
for _, chirp:= range dbchirps{
chirps = append(chirps, Chirp{
ID: chirp.ID,
Body: chirp.Body,
UserID: chirp.UserID,
CreatedAt: chirp.CreatedAt,
UpdatedAt: chirp.UpdatedAt,
})
}
respondWithJson(w, http.StatusOK, chirps)
}