This repository has been archived by the owner on Sep 19, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 22
/
daterange.go
72 lines (58 loc) · 1.54 KB
/
daterange.go
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package api
import "encoding/json"
// DateRange is a basic input.
type DateRange struct {
PayloadFrom Payload `json:"from" sql:"-"`
PayloadTo Payload `json:"to" sql:"-"`
Present bool `json:"present"`
// Validator specific fields
From *DateControl `json:"-"`
To *DateControl `json:"-"`
// Persister specific fields
ID int `json:"-"`
AccountID int `json:"-"`
FromID int `json:"-"`
ToID int `json:"-"`
}
// Unmarshal bytes in to the entity properties.
func (entity *DateRange) Unmarshal(raw []byte) error {
err := json.Unmarshal(raw, entity)
if err != nil {
return err
}
from, err := entity.PayloadFrom.Entity()
if err != nil {
return err
}
entity.From = from.(*DateControl)
to, err := entity.PayloadTo.Entity()
if err != nil {
return err
}
entity.To = to.(*DateControl)
return err
}
// Marshal to payload structure
func (entity *DateRange) Marshal() Payload {
if entity.From != nil {
entity.PayloadFrom = entity.From.Marshal()
}
if entity.To != nil {
entity.PayloadTo = entity.To.Marshal()
}
return MarshalPayloadEntity("daterange", entity)
}
// Valid checks the value(s) against an battery of tests.
func (entity *DateRange) Valid() (bool, error) {
var stack ErrorStack
if ok, err := entity.From.Valid(); !ok {
stack.Append("From", err)
}
if ok, err := entity.To.Valid(); !ok {
stack.Append("To", err)
}
if !stack.HasErrors() && entity.From.Date().After(entity.To.Date()) {
stack.Append("Range", ErrFieldRequired{"Date range is out of order"})
}
return !stack.HasErrors(), stack
}