-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathget_chirps.go
More file actions
54 lines (47 loc) · 1.22 KB
/
Copy pathget_chirps.go
File metadata and controls
54 lines (47 loc) · 1.22 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
package main
import (
"net/http"
"sort"
"github.com/google/uuid"
"github.com/nk-reddy/chirpy/internal/database"
)
func (cfg *apiConfig) handlerGetAllChirps(w http.ResponseWriter, r *http.Request) {
chirps := []database.Chirp{}
var err error
s := r.URL.Query().Get("author_id")
if s != "" {
authorID, err := uuid.Parse(s)
if err != nil {
respondWithError(w, http.StatusBadRequest, "invalid author ID")
return
}
chirps, err = cfg.db.GetChirpsByAuthor(r.Context(), authorID)
} else {
chirps, err = cfg.db.GetChirps(r.Context())
}
if err != nil {
respondWithError(w, http.StatusInternalServerError, err.Error())
return
}
response := make([]chirpResponse, len(chirps))
for i, chirp := range chirps {
response[i] = chirpResponse{
ID: chirp.ID,
CreatedAt: chirp.CreatedAt,
UpdatedAt: chirp.UpdatedAt,
Body: chirp.Body,
UserID: chirp.UserID,
}
}
s2 := r.URL.Query().Get("sort")
if s2 == "desc" {
sort.Slice(response, func(i, j int) bool {
return response[i].CreatedAt.After(response[j].CreatedAt)
})
} else {
sort.Slice(response, func(i, j int) bool {
return response[i].CreatedAt.Before(response[j].CreatedAt)
})
}
respondWithJSON(w, http.StatusOK, response)
}