forked from rs/rest-layer
/
time.go
86 lines (79 loc) · 1.95 KB
/
time.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package schema
import (
"context"
"errors"
"time"
)
var (
// Now is a field hook handler that returns the current time, to be used in
// schema with OnInit and OnUpdate.
Now = func(ctx context.Context, value interface{}) interface{} {
return time.Now()
}
// CreatedField is a common schema field configuration for "created" fields. It stores
// the creation date of the item.
CreatedField = Field{
Description: "The time at which the item has been inserted",
Required: true,
ReadOnly: true,
OnInit: Now,
Sortable: true,
Validator: &Time{},
}
// UpdatedField is a common schema field configuration for "updated" fields. It stores
// the current date each time the item is modified.
UpdatedField = Field{
Description: "The time at which the item has been last updated",
Required: true,
ReadOnly: true,
OnInit: Now,
OnUpdate: Now,
Sortable: true,
Validator: &Time{},
}
formats = []string{
time.RFC3339,
time.RFC3339Nano,
time.ANSIC,
time.UnixDate,
time.RubyDate,
time.RFC822,
time.RFC822Z,
time.RFC850,
time.RFC1123,
time.RFC1123Z,
}
)
// Time validates time based values
type Time struct {
TimeLayouts []string // TimeLayouts is set of time layouts we want to validate
layouts []string
}
// Compile the time formats
func (v *Time) Compile() (err error) {
if len(v.TimeLayouts) == 0 {
// default layouts to all formats
v.layouts = formats
return nil
}
// User specified list of time layouts
for _, layout := range v.TimeLayouts {
v.layouts = append(v.layouts, string(layout))
}
return nil
}
// Validate validates and normalize time based value
func (v Time) Validate(value interface{}) (interface{}, error) {
if s, ok := value.(string); ok {
for _, layout := range v.layouts {
if t, err := time.Parse(layout, s); err == nil {
value = t
break
}
}
}
if _, ok := value.(time.Time); !ok {
return nil, errors.New("not a time")
}
return value, nil
}