feat: added sorting and retrieving by author to chirps endpoint

This commit is contained in:
Stevan Freeborn
2026-08-15 21:35:53 -05:00
parent d34c7b5822
commit aaa913ccab
4 changed files with 88 additions and 3 deletions
+48 -3
View File
@@ -289,8 +289,53 @@ func (s *server) HandleCreateUser(w http.ResponseWriter, r *http.Request) {
})
}
func (s *server) HandleGetAllChirps(w http.ResponseWriter, r *http.Request) {
existingChirps, err := s.database.GetAllChirps(r.Context())
const (
Ascending = "asc"
Descending = "desc"
)
func (s *server) HandleGetChirps(w http.ResponseWriter, r *http.Request) {
authorId := r.URL.Query().Get("author_id")
sortDir := r.URL.Query().Get("sort")
hasAuthorId := strings.TrimSpace(authorId) != ""
hasSort := strings.TrimSpace(sortDir) != ""
validAuthorId, err := uuid.Parse(authorId)
if hasAuthorId && err != nil {
writeJsonResponse(w, http.StatusBadRequest, apiError{
Err: "Author id must be a valid uuid",
})
return
}
if hasSort && sortDir != Ascending && sortDir != Descending {
writeJsonResponse(w, http.StatusBadRequest, apiError{
Err: fmt.Sprintf("Sort direction must be either '%s' or '%s'", Ascending, Descending),
})
return
}
if !hasSort {
sortDir = "asc"
}
var existingChirps []database.Chirp
if hasAuthorId {
existingChirps, err = s.database.GetChirpsByAuthor(r.Context(), validAuthorId)
} else {
existingChirps, err = s.database.GetAllChirps(r.Context())
}
slices.SortFunc(existingChirps, func(a, b database.Chirp) int {
if sortDir == Descending {
return b.CreatedAt.Compare(a.CreatedAt)
}
return a.CreatedAt.Compare(b.CreatedAt)
})
if err != nil {
writeJsonResponse(w, http.StatusInternalServerError, apiError{
@@ -800,7 +845,7 @@ func main() {
mux.HandleFunc("PUT /api/users", server.HandleUpdateUser)
mux.HandleFunc("POST /api/polka/webhooks", server.HandleWebhooks)
mux.HandleFunc("GET /api/chirps", server.HandleGetAllChirps)
mux.HandleFunc("GET /api/chirps", server.HandleGetChirps)
mux.HandleFunc("GET /api/chirps/{id}", server.HandleGetChirp)
mux.HandleFunc("POST /api/chirps", server.HandleCreateChirp)
mux.HandleFunc("DELETE /api/chirps/{id}", server.HandleDeleteChirp)