all repos

onasty @ 4137dee

a one-time notes service

onasty/internal/models/note.go (view raw)

Olexandr Smirnov Olexandr Smirnov
ss2316544@gmail.com
feat(api): validate user provided slug (#164)..., 11 months ago
1
package models
2
3
import (
4
	"errors"
5
	"strings"
6
	"time"
7
8
	"github.com/gofrs/uuid/v5"
9
)
10
11
var (
12
	ErrNoteContentIsEmpty     = errors.New("note: content is empty")
13
	ErrNoteSlugIsAlreadyInUse = errors.New("note: slug is already in use")
14
	ErrNoteSlugIsInvalid      = errors.New("note: slug is invalid")
15
	ErrNoteExpired            = errors.New("note: expired")
16
	ErrNoteNotFound           = errors.New("note: not found")
17
)
18
19
type Note struct {
20
	ID                   uuid.UUID
21
	Content              string
22
	Slug                 string
23
	Password             string
24
	BurnBeforeExpiration bool
25
	ReadAt               time.Time
26
	CreatedAt            time.Time
27
	ExpiresAt            time.Time
28
}
29
30
func (n Note) Validate() error {
31
	if n.Content == "" {
32
		return ErrNoteContentIsEmpty
33
	}
34
35
	if n.Slug == "" || strings.Contains(n.Slug, " ") {
36
		return ErrNoteSlugIsInvalid
37
	}
38
39
	if n.IsExpired() {
40
		return ErrNoteExpired
41
	}
42
43
	return nil
44
}
45
46
func (n Note) IsExpired() bool {
47
	return !n.ExpiresAt.IsZero() &&
48
		n.ExpiresAt.Before(time.Now())
49
}
50
51
func (n Note) ShouldBeBurnt() bool {
52
	return !n.ExpiresAt.IsZero() &&
53
		n.BurnBeforeExpiration
54
}
55
56
func (n Note) IsRead() bool {
57
	return !n.ReadAt.IsZero()
58
}