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 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 |
package apiv1
import (
"errors"
"io"
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/olexsmir/onasty/internal/dtos"
"github.com/olexsmir/onasty/internal/models"
"github.com/olexsmir/onasty/internal/service/notesrv"
)
type createNoteRequest struct {
Content string `json:"content"`
Slug string `json:"slug"`
Password string `json:"password"`
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(),
Password: req.Password,
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.CreateNote{
Content: note.Content,
UserID: a.getUserID(c),
Slug: note.Slug,
Password: note.Password,
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 getNoteBySlugRequest struct {
Password string `json:"password"`
}
type getNoteBySlugResponse struct {
Content string `json:"content"`
ReadAt time.Time `json:"read_at,omitzero"`
CreatedAt time.Time `json:"created_at"`
ExpiresAt time.Time `json:"expires_at,omitzero"`
}
func (a *APIV1) getNoteBySlugHandler(c *gin.Context) {
var req getNoteBySlugRequest
if err := c.ShouldBindJSON(&req); err != nil && !errors.Is(err, io.EOF) {
newError(c, http.StatusBadRequest, "invalid request")
return
}
note, err := a.notesrv.GetBySlugAndRemoveIfNeeded(
c.Request.Context(),
notesrv.GetNoteBySlugInput{
Slug: c.Param("slug"),
Password: req.Password,
},
)
if err != nil {
errorResponse(c, err)
return
}
status := http.StatusOK
if !note.ReadAt.IsZero() {
status = http.StatusNotFound
}
c.JSON(status, getNoteBySlugResponse{
Content: note.Content,
ReadAt: note.ReadAt,
CreatedAt: note.CreatedAt,
ExpiresAt: note.ExpiresAt,
})
}
|