-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchirp-get.go
More file actions
84 lines (66 loc) · 1.96 KB
/
chirp-get.go
File metadata and controls
84 lines (66 loc) · 1.96 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
78
79
80
81
82
83
84
package main
import (
"log"
"net/http"
"sort"
"github.com/google/uuid"
"github.com/mdmdj/bootdev-chirpy/internal/database"
)
func chirpGetAllRoute(w http.ResponseWriter, r *http.Request) {
authorID := r.URL.Query().Get("author_id")
var dbChirps []database.Chirp
var err error
authorUUID, err := uuid.Parse(authorID)
if authorID == "" || err != nil {
// authorID was not supplied or could not parse to UUID
// so we just get all Chirps
dbChirps, err = cfg.db.GetAllChirps(r.Context())
} else {
// authorID parsed to UUID so it might be valid author ID
// so we'll try to get chirps with it
dbChirps, err = cfg.db.GetAllChirpsByAuthor(r.Context(), authorUUID)
}
if err != nil {
log.Printf("Error getting chirps: %s", err)
respondWithError(w, http.StatusInternalServerError, "Something went wrong")
return
}
var chirps []Chirp
for _, v := range dbChirps {
chirps = append(chirps, Chirp{
ID: v.ID,
UserID: v.UserID,
Body: v.Body,
CreatedAt: v.CreatedAt,
UpdatedAt: v.UpdatedAt,
})
}
sortType := r.URL.Query().Get("sort")
if sortType == "desc" {
sort.SliceStable(chirps, func(i, j int) bool { return chirps[i].CreatedAt.After(chirps[j].CreatedAt) })
}
respondWithJSON(w, http.StatusOK, chirps)
}
func chirpGetOneRoute(w http.ResponseWriter, r *http.Request) {
chirpID := r.PathValue("chirpID")
chirpUUID, err := uuid.Parse(chirpID)
if chirpID == "" || err != nil {
log.Printf("Error getting chirp, bad ID: %s", chirpID)
respondWithError(w, http.StatusNotFound, "404 Chirp Not Found")
return
}
dbChirp, err := cfg.db.GetOneChirp(r.Context(), chirpUUID)
if err != nil {
log.Printf("Error getting chirp: %s %s", chirpID, err)
respondWithError(w, http.StatusNotFound, "404 Chirp Not Found")
return
}
chirp := Chirp{
ID: dbChirp.ID,
UserID: dbChirp.UserID,
Body: dbChirp.Body,
CreatedAt: dbChirp.CreatedAt,
UpdatedAt: dbChirp.UpdatedAt,
}
respondWithJSON(w, http.StatusOK, chirp)
}