| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "net/http" |
| 5 | "strings" |
| 6 | |
| 7 | "github.com/stevedylandev/andromeda/pkg/web" |
| 8 | ) |
| 9 | |
| 10 | func (a *App) apiListNotes(w http.ResponseWriter, r *http.Request) { |
| 11 | notes, err := listNotes(a.DB) |
| 12 | if err != nil { |
| 13 | web.WriteError(w, http.StatusInternalServerError, err.Error()) |
| 14 | return |
| 15 | } |
| 16 | if notes == nil { |
| 17 | notes = []Note{} |
| 18 | } |
| 19 | web.WriteJSON(w, http.StatusOK, notes) |
| 20 | } |
| 21 | |
| 22 | func (a *App) apiGetNote(w http.ResponseWriter, r *http.Request) { |
| 23 | shortID := r.PathValue("short_id") |
| 24 | note, err := getNoteByShortID(a.DB, shortID) |
| 25 | if err != nil { |
| 26 | web.WriteError(w, http.StatusInternalServerError, err.Error()) |
| 27 | return |
| 28 | } |
| 29 | if note == nil { |
| 30 | http.NotFound(w, r) |
| 31 | return |
| 32 | } |
| 33 | web.WriteJSON(w, http.StatusOK, note) |
| 34 | } |
| 35 | |
| 36 | func (a *App) apiCreateNote(w http.ResponseWriter, r *http.Request) { |
| 37 | var body NoteInput |
| 38 | if !web.DecodeJSON(w, r, &body) { |
| 39 | return |
| 40 | } |
| 41 | title := strings.TrimSpace(body.Title) |
| 42 | if title == "" { |
| 43 | http.Error(w, "title required", http.StatusBadRequest) |
| 44 | return |
| 45 | } |
| 46 | note, err := createNote(a.DB, title, body.Content) |
| 47 | if err != nil { |
| 48 | web.WriteError(w, http.StatusInternalServerError, err.Error()) |
| 49 | return |
| 50 | } |
| 51 | web.WriteJSON(w, http.StatusCreated, note) |
| 52 | } |
| 53 | |
| 54 | func (a *App) apiUpdateNote(w http.ResponseWriter, r *http.Request) { |
| 55 | shortID := r.PathValue("short_id") |
| 56 | var body NoteInput |
| 57 | if !web.DecodeJSON(w, r, &body) { |
| 58 | return |
| 59 | } |
| 60 | title := strings.TrimSpace(body.Title) |
| 61 | if title == "" { |
| 62 | http.Error(w, "title required", http.StatusBadRequest) |
| 63 | return |
| 64 | } |
| 65 | note, err := updateNoteByShortID(a.DB, shortID, title, body.Content) |
| 66 | if err != nil { |
| 67 | web.WriteError(w, http.StatusInternalServerError, err.Error()) |
| 68 | return |
| 69 | } |
| 70 | if note == nil { |
| 71 | http.NotFound(w, r) |
| 72 | return |
| 73 | } |
| 74 | web.WriteJSON(w, http.StatusOK, note) |
| 75 | } |
| 76 | |
| 77 | func (a *App) apiDeleteNote(w http.ResponseWriter, r *http.Request) { |
| 78 | shortID := r.PathValue("short_id") |
| 79 | ok, err := deleteNoteByShortID(a.DB, shortID) |
| 80 | if err != nil { |
| 81 | web.WriteError(w, http.StatusInternalServerError, err.Error()) |
| 82 | return |
| 83 | } |
| 84 | if !ok { |
| 85 | http.NotFound(w, r) |
| 86 | return |
| 87 | } |
| 88 | w.WriteHeader(http.StatusNoContent) |
| 89 | } |