summaryrefslogtreecommitdiff
path: root/app/domain/sparkle.go
blob: 5ed73dfd1f3e454ac7a483f031eacaa84aa24979 (plain)
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
package domain

import (
	"errors"
	"regexp"

	"github.com/xlgmokha/x/pkg/x"
)

type Sparkle struct {
	Sparklee string `json:"sparklee" jsonapi:"attr,sparklee"`
	Author   *User  `json:"author" jsonapi:"attr,author"`
	Reason   string `json:"reason" jsonapi:"attr,reason"`
	entity
}

var SparkleRegex = regexp.MustCompile(`\A\s*(?P<sparklee>@\w+)\s+(?P<reason>.+)\z`)
var SparkleeIndex = SparkleRegex.SubexpIndex("sparklee")
var ReasonIndex = SparkleRegex.SubexpIndex("reason")

var ReasonIsRequired = errors.New("Reason is required")
var SparkleeIsRequired = errors.New("Sparklee is required")

func WithText(text string) x.Option[*Sparkle] {
	return x.With(func(item *Sparkle) {
		if len(text) == 0 {
			return
		}

		matches := SparkleRegex.FindStringSubmatch(text)
		if len(matches) == 0 {
			return
		}

		item.Sparklee = matches[SparkleeIndex]
		item.Reason = matches[ReasonIndex]
	})
}

func (s *Sparkle) ToGID() GlobalID {
	return GlobalID("gid://sparkle/Sparkle/" + s.ID.String())
}

func (s *Sparkle) Validate() error {
	if x.IsZero(s.Sparklee) {
		return SparkleeIsRequired
	}
	if x.IsZero(s.Reason) {
		return ReasonIsRequired
	}
	return nil
}