| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "net/http" |
| 5 | "strconv" |
| 6 | |
| 7 | "github.com/stevedylandev/andromeda/pkg/web" |
| 8 | ) |
| 9 | |
| 10 | func (a *App) apiListQuotes(w http.ResponseWriter, r *http.Request) { |
| 11 | limit := 100 |
| 12 | if v := r.URL.Query().Get("limit"); v != "" { |
| 13 | if n, err := strconv.Atoi(v); err == nil && n > 0 && n <= 500 { |
| 14 | limit = n |
| 15 | } |
| 16 | } |
| 17 | quotes, err := listQuotes(a.DB, limit) |
| 18 | if err != nil { |
| 19 | a.Log.Error("list quotes", "err", err) |
| 20 | w.WriteHeader(http.StatusInternalServerError) |
| 21 | return |
| 22 | } |
| 23 | if quotes == nil { |
| 24 | quotes = []Quote{} |
| 25 | } |
| 26 | web.WriteJSON(w, http.StatusOK, quotes) |
| 27 | } |
| 28 | |
| 29 | func (a *App) apiQuoteOfTheDay(w http.ResponseWriter, r *http.Request) { |
| 30 | q, err := quoteOfTheDay(a.DB) |
| 31 | if err != nil { |
| 32 | a.Log.Error("quote of the day", "err", err) |
| 33 | w.WriteHeader(http.StatusInternalServerError) |
| 34 | return |
| 35 | } |
| 36 | if q == nil { |
| 37 | web.WriteError(w, http.StatusNotFound, "no quotes") |
| 38 | return |
| 39 | } |
| 40 | web.WriteJSON(w, http.StatusOK, q) |
| 41 | } |
| 42 | |
| 43 | func (a *App) apiRandomQuote(w http.ResponseWriter, r *http.Request) { |
| 44 | q, err := randomQuote(a.DB) |
| 45 | if err != nil { |
| 46 | a.Log.Error("random quote", "err", err) |
| 47 | w.WriteHeader(http.StatusInternalServerError) |
| 48 | return |
| 49 | } |
| 50 | if q == nil { |
| 51 | web.WriteError(w, http.StatusNotFound, "no quotes") |
| 52 | return |
| 53 | } |
| 54 | web.WriteJSON(w, http.StatusOK, q) |
| 55 | } |
| 56 | |
| 57 | func (a *App) apiGetQuote(w http.ResponseWriter, r *http.Request) { |
| 58 | q, err := getQuoteByShortID(a.DB, r.PathValue("short_id")) |
| 59 | if err != nil { |
| 60 | a.Log.Error("get quote", "err", err) |
| 61 | w.WriteHeader(http.StatusInternalServerError) |
| 62 | return |
| 63 | } |
| 64 | if q == nil { |
| 65 | web.WriteError(w, http.StatusNotFound, "not found") |
| 66 | return |
| 67 | } |
| 68 | web.WriteJSON(w, http.StatusOK, q) |
| 69 | } |