-
Notifications
You must be signed in to change notification settings - Fork 1
/
null-time.go
100 lines (84 loc) · 1.91 KB
/
null-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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package gql
import (
"bytes"
"database/sql/driver"
"fmt"
"io"
"strings"
"time"
)
// NullTime implements a nullable timestamp for sql
// swagger:type string
type NullTime struct {
Time time.Time
Valid bool // Valid is true if String is not NULL
}
// Scan implements the SQL Scanner interface for NullTime.
func (n *NullTime) Scan(value interface{}) (err error) {
n.Valid = true
switch value := value.(type) {
case time.Time:
n.Time = value
default:
n.Time, n.Valid = time.Time{}, false
}
return
}
// Value implements the SQL driver Valuer interface.
func (n NullTime) Value() (driver.Value, error) {
if !n.Valid {
return nil, nil
}
return n.Time, nil
}
// UnmarshalGQL implements the graphql.Marshaler interface for NullTime
func (n *NullTime) UnmarshalGQL(v interface{}) (err error) {
value, ok := v.(string)
if !ok {
return fmt.Errorf("points must be strings")
}
if value == "null" {
n.Valid = false
n.Time = time.Time{}
} else {
n.Valid = true
n.Time, err = time.Parse(time.RFC3339, strings.Trim(value, ` "`))
}
return
}
// MarshalGQL implements the graphql.Marshaler interface for NullTime
func (n NullTime) MarshalGQL(w io.Writer) {
var err error
if n.Valid {
_, err = w.Write([]byte(`"` + n.Time.Format(time.RFC3339+`"`)))
} else {
_, err = w.Write([]byte(`null`))
}
if err != nil {
return
}
}
// UnmarshalJSON implements the json.Marshaler interface for NullTime
func (n *NullTime) UnmarshalJSON(in []byte) (err error) {
if bytes.Equal(in, []byte(`null`)) {
n.Valid = false
return
}
in = bytes.Trim(in, `"`)
n.Time, err = time.Parse(time.RFC3339, string(in))
if err != nil {
n.Valid = false
return
}
n.Valid = true
return
}
// MarshalJSON implements the json.Marshaler interface for NullTime
func (n NullTime) MarshalJSON() (out []byte, err error) {
if n.Valid {
out = []byte(`"` + n.Time.Format(time.RFC3339) + `"`)
} else {
out = []byte("null")
}
return
}