main
1package domain
2
3import (
4 "errors"
5 "regexp"
6
7 "gitlab.com/mokhax/sparkled/pkg/pls"
8)
9
10type Sparkle struct {
11 ID string `json:"id" jsonapi:"primary,sparkles"`
12 Sparklee string `json:"sparklee" jsonapi:"attr,sparklee"`
13 Reason string `json:"reason" jsonapi:"attr,reason"`
14}
15
16var SparkleRegex = regexp.MustCompile(`\A\s*(?P<sparklee>@\w+)\s+(?P<reason>.+)\z`)
17var SparkleeIndex = SparkleRegex.SubexpIndex("sparklee")
18var ReasonIndex = SparkleRegex.SubexpIndex("reason")
19
20var ReasonIsRequired = errors.New("Reason is required")
21var SparkleIsEmpty = errors.New("Sparkle is empty")
22var SparkleIsInvalid = errors.New("Sparkle is invalid")
23var SparkleeIsRequired = errors.New("Sparklee is required")
24
25func NewSparkle(text string) (*Sparkle, error) {
26 if len(text) == 0 {
27 return nil, SparkleIsEmpty
28 }
29
30 matches := SparkleRegex.FindStringSubmatch(text)
31 if len(matches) == 0 {
32 return nil, SparkleIsInvalid
33 }
34
35 return &Sparkle{
36 ID: pls.GenerateULID(),
37 Sparklee: matches[SparkleeIndex],
38 Reason: matches[ReasonIndex],
39 }, nil
40}
41
42func (s *Sparkle) Validate() error {
43 if s.Sparklee == "" {
44 return SparkleeIsRequired
45 }
46 if s.Reason == "" {
47 return ReasonIsRequired
48 }
49 return nil
50}