all repos

onasty @ ff7bfce

a one-time notes service

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

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