package httpapi import ( "errors" "net/http" "github.com/gin-gonic/gin" "git.kmalloc.org/squid/sonda/internal/feedback" ) // feedbackHandlers serve the signed-in user's wishlist and the artists they are // not interested in. Both are theirs alone. type feedbackHandlers struct{ svc feedbackService } type markedJSON struct { Artist artistRefJSON `json:"artist"` InLibrary bool `json:"in_library"` MarkedAt string `json:"marked_at"` } type markedPageJSON struct { Items []markedJSON `json:"items"` Total int `json:"total"` Limit int `json:"limit"` Offset int `json:"offset"` } func writeFeedbackError(c *gin.Context, err error) { switch { case errors.Is(err, feedback.ErrArtistNotFound): writeError(c, http.StatusNotFound, "artist_not_found", "no such artist") case errors.Is(err, feedback.ErrUserNotFound): writeError(c, http.StatusUnauthorized, "unauthorized", "account no longer exists") case errors.Is(err, feedback.ErrInvalidQuery): writeError(c, http.StatusBadRequest, "invalid_input", err.Error()) default: _ = c.Error(err) writeError(c, http.StatusInternalServerError, "internal", "internal error") } } // add marks the artist of the path. It answers 204, also when it was marked already. func (h *feedbackHandlers) add(kind feedback.Kind) gin.HandlerFunc { return func(c *gin.Context) { id, ok := pathID(c) if !ok { return } if err := h.svc.Add(c.Request.Context(), currentUserID(c), id, kind); err != nil { writeFeedbackError(c, err) return } c.Status(http.StatusNoContent) } } // remove takes the mark off. It answers 204, also when there was none. func (h *feedbackHandlers) remove(kind feedback.Kind) gin.HandlerFunc { return func(c *gin.Context) { id, ok := pathID(c) if !ok { return } if err := h.svc.Remove(c.Request.Context(), currentUserID(c), id, kind); err != nil { writeFeedbackError(c, err) return } c.Status(http.StatusNoContent) } } func (h *feedbackHandlers) list(kind feedback.Kind) gin.HandlerFunc { return func(c *gin.Context) { limit, ok := queryInt(c, "limit") if !ok { return } offset, ok := queryInt(c, "offset") if !ok { return } page, err := h.svc.List(c.Request.Context(), currentUserID(c), kind, feedback.Page{Limit: clampInt(limit), Offset: clampInt(offset)}) if err != nil { writeFeedbackError(c, err) return } out := markedPageJSON{Items: make([]markedJSON, len(page.Items)), Total: page.Total, Limit: page.Limit, Offset: page.Offset} for i, e := range page.Items { out.Items[i] = markedJSON{ Artist: artistRefJSON{ID: e.Artist.ID, Name: e.Artist.Name}, InLibrary: e.InLibrary, MarkedAt: *rfc3339(e.At), } } c.JSON(http.StatusOK, out) } }