summaryrefslogtreecommitdiff
path: root/pkg/domain/sparkle.go
blob: 54ccb13782b49a36dc0ecbb52cb7f2fedef4e856 (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
package domain

import (
	"errors"
	"regexp"

	"gitlab.com/mokhax/sparkled/pkg/pls"
)

type Sparkle struct {
	ID       string `json:"id" jsonapi:"primary,sparkles"`
	Sparklee string `json:"sparklee" jsonapi:"attr,sparklee"`
	Reason   string `json:"reason" jsonapi:"attr,reason"`
}

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 SparkleIsEmpty = errors.New("Sparkle is empty")
var SparkleIsInvalid = errors.New("Sparkle is invalid")
var SparkleeIsRequired = errors.New("Sparklee is required")

func NewSparkle(text string) (*Sparkle, error) {
	if len(text) == 0 {
		return nil, SparkleIsEmpty
	}

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

	return &Sparkle{
		ID:       pls.GenerateULID(),
		Sparklee: matches[SparkleeIndex],
		Reason:   matches[ReasonIndex],
	}, nil
}

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