forked from bootdotdev/learn-cicd-starter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler_notes.go
53 lines (46 loc) · 1.37 KB
/
handler_notes.go
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
package main
import (
"encoding/json"
"net/http"
"time"
"github.com/bootdotdev/learn-cicd-starter/internal/database"
"github.com/google/uuid"
)
func (cfg *apiConfig) handlerNotesGet(w http.ResponseWriter, r *http.Request, user database.User) {
posts, err := cfg.DB.GetNotesForUser(r.Context(), user.ID)
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Couldn't get posts for user")
return
}
respondWithJSON(w, http.StatusOK, databasePostsToPosts(posts))
}
func (cfg *apiConfig) handlerNotesCreate(w http.ResponseWriter, r *http.Request, user database.User) {
type parameters struct {
Note string `json:"note"`
}
decoder := json.NewDecoder(r.Body)
params := parameters{}
err := decoder.Decode(¶ms)
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Couldn't decode parameters")
return
}
id := uuid.New().String()
err = cfg.DB.CreateNote(r.Context(), database.CreateNoteParams{
ID: id,
CreatedAt: time.Now().UTC(),
UpdatedAt: time.Now().UTC(),
Note: params.Note,
UserID: user.ID,
})
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Couldn't create note")
return
}
note, err := cfg.DB.GetNote(r.Context(), id)
if err != nil {
respondWithError(w, http.StatusNotFound, "Couldn't get note")
return
}
respondWithJSON(w, http.StatusCreated, databaseNoteToNote(note))
}