all repos

onasty @ e075c32

a one-time notes service

onasty/internal/transport/http/apiv1/note.go (view raw)

Smirnov Oleksandr Smirnov Oleksandr
ss2316544@gmail.com
refactor: make NoteSlugDTO type as string alias (#19), 1 year ago
1
package apiv1
2
3
import (
4
	"net/http"
5
	"time"
6
7
	"github.com/gin-gonic/gin"
8
	"github.com/olexsmir/onasty/internal/dtos"
9
	"github.com/olexsmir/onasty/internal/models"
10
)
11
12
type createNoteRequest struct {
13
	Content              string    `json:"content"`
14
	Slug                 string    `json:"slug"`
15
	BurnBeforeExpiration bool      `json:"burn_before_expiration"`
16
	ExpiresAt            time.Time `json:"expires_at"`
17
}
18
19
type createNoteResponse struct {
20
	Slug string `json:"slug"`
21
}
22
23
func (a *APIV1) createNoteHandler(c *gin.Context) {
24
	var req createNoteRequest
25
	if err := c.ShouldBindJSON(&req); err != nil {
26
		newError(c, http.StatusBadRequest, "invalid request")
27
		return
28
	}
29
30
	note := models.Note{ //nolint:exhaustruct
31
		Content:              req.Content,
32
		Slug:                 req.Slug,
33
		BurnBeforeExpiration: req.BurnBeforeExpiration,
34
		CreatedAt:            time.Now(),
35
		ExpiresAt:            req.ExpiresAt,
36
	}
37
38
	if err := note.Validate(); err != nil {
39
		newErrorStatus(c, http.StatusBadRequest, err.Error())
40
		return
41
	}
42
43
	slug, err := a.notesrv.Create(c.Request.Context(), dtos.CreateNoteDTO{
44
		Content:              note.Content,
45
		UserID:               a.getUserID(c),
46
		Slug:                 note.Slug,
47
		BurnBeforeExpiration: note.BurnBeforeExpiration,
48
		CreatedAt:            note.CreatedAt,
49
		ExpiresAt:            note.ExpiresAt,
50
	}, a.getUserID(c))
51
	if err != nil {
52
		errorResponse(c, err)
53
		return
54
	}
55
56
	c.JSON(http.StatusCreated, createNoteResponse{slug})
57
}
58
59
type getNoteBySlugResponse struct {
60
	Content   string    `json:"content"`
61
	CratedAt  time.Time `json:"crated_at"`
62
	ExpiresAt time.Time `json:"expires_at"`
63
}
64
65
func (a *APIV1) getNoteBySlugHandler(c *gin.Context) {
66
	slug := c.Param("slug")
67
	note, err := a.notesrv.GetBySlugAndRemoveIfNeeded(c.Request.Context(), slug)
68
	if err != nil {
69
		errorResponse(c, err)
70
		return
71
	}
72
73
	c.JSON(http.StatusOK, getNoteBySlugResponse{
74
		Content:   note.Content,
75
		CratedAt:  note.CreatedAt,
76
		ExpiresAt: note.ExpiresAt,
77
	})
78
}