-
Notifications
You must be signed in to change notification settings - Fork 0
/
date.go
72 lines (61 loc) · 1.45 KB
/
date.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 scalars
import (
"github.com/pkg/errors"
"github.com/weavingwebs/wwgo"
"io"
"time"
)
const GqlDateFormat = "2006-01-02"
type GqlDate time.Time
func (d GqlDate) Time() time.Time {
return time.Time(d)
}
func (d GqlDate) String() string {
return d.Time().Format(GqlDateFormat)
}
func (d *GqlDate) UnmarshalGQL(v interface{}) error {
if v == nil {
return nil
}
str, ok := v.(string)
if !ok {
return errors.Errorf("invalid type %T, expected string", v)
}
t, err := time.Parse(GqlDateFormat, str)
if err != nil {
return wwgo.NewClientError("GQL_DATE_PARSE_EXCEPTION", "Invalid Date", err)
}
*d = GqlDate(t)
return nil
}
func (d GqlDate) MarshalGQL(w io.Writer) {
if d.Time().IsZero() {
_, _ = w.Write([]byte("null"))
return
}
_, _ = w.Write([]byte(`"`))
_, _ = w.Write([]byte(d.String()))
_, _ = w.Write([]byte(`"`))
}
func (d *GqlDate) UnmarshalJSON(data []byte) error {
// Ignore null, like in the main JSON package.
if string(data) == "null" {
return nil
}
t, err := time.Parse(`"`+GqlDateFormat+`"`, string(data))
*d = GqlDate(t)
return err
}
func (d GqlDate) MarshalJSON() ([]byte, error) {
if d.Time().IsZero() {
return []byte("null"), nil
}
if y := d.Time().Year(); y < 0 || y >= 10000 {
return nil, errors.New("GqlDate.MarshalJSON: year outside of range [0,9999]")
}
b := make([]byte, 0, len(GqlDateFormat)+2)
b = append(b, '"')
b = d.Time().AppendFormat(b, GqlDateFormat)
b = append(b, '"')
return b, nil
}