onasty/internal/transport/http/apiv1/note.go(view raw)
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 |
package apiv1
import (
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/olexsmir/onasty/internal/dtos"
"github.com/olexsmir/onasty/internal/models"
)
type createNoteRequest struct {
Content string `json:"content"`
Slug string `json:"slug"`
BurnBeforeExpiration bool `json:"burn_before_expiration"`
ExpiresAt time.Time `json:"expires_at"`
}
type createNoteResponse struct {
Slug string `json:"slug"`
}
func (a *APIV1) createNoteHandler(c *gin.Context) {
var req createNoteRequest
if err := c.ShouldBindJSON(&req); err != nil {
newError(c, http.StatusBadRequest, "invalid request")
return
}
note := models.Note{ //nolint:exhaustruct
Content: req.Content,
Slug: req.Slug,
BurnBeforeExpiration: req.BurnBeforeExpiration,
CreatedAt: time.Now(),
ExpiresAt: req.ExpiresAt,
}
if err := note.Validate(); err != nil {
newErrorStatus(c, http.StatusBadRequest, err.Error())
return
}
slug, err := a.notesrv.Create(c.Request.Context(), dtos.CreateNoteDTO{
Content: note.Content,
UserID: a.getUserID(c),
Slug: note.Slug,
BurnBeforeExpiration: note.BurnBeforeExpiration,
CreatedAt: note.CreatedAt,
ExpiresAt: note.ExpiresAt,
}, a.getUserID(c))
if err != nil {
errorResponse(c, err)
return
}
c.JSON(http.StatusCreated, createNoteResponse{slug})
}
type getNoteBySlugResponse struct {
Content string `json:"content"`
CratedAt time.Time `json:"crated_at"`
ExpiresAt time.Time `json:"expires_at"`
}
func (a *APIV1) getNoteBySlugHandler(c *gin.Context) {
slug := c.Param("slug")
note, err := a.notesrv.GetBySlugAndRemoveIfNeeded(c.Request.Context(), slug)
if err != nil {
errorResponse(c, err)
return
}
c.JSON(http.StatusOK, getNoteBySlugResponse{
Content: note.Content,
CratedAt: note.CreatedAt,
ExpiresAt: note.ExpiresAt,
})
}
|