This repository has been archived by the owner on Apr 2, 2024. It is now read-only.
generated from mrz1836/go-template
-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
nulltime.go
115 lines (93 loc) · 2.3 KB
/
nulltime.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package utils
import (
"database/sql"
"encoding/json"
"time"
"github.com/99designs/gqlgen/graphql"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/bsontype"
)
// NullTime wrapper around sql.NullTime
type NullTime struct {
sql.NullTime
}
// IsZero method is called by bson.IsZero in Mongo for type = NullTime
func (x NullTime) IsZero() bool {
return !x.Valid
}
// MarshalNullTime is used by GraphQL to marshal the value
func MarshalNullTime(x NullTime) graphql.Marshaler {
if !x.Valid {
return graphql.Null
}
return graphql.MarshalTime(x.Time)
}
// UnmarshalNullTime is used by GraphQL to unmarshal the value
func UnmarshalNullTime(t interface{}) (NullTime, error) {
if t == nil {
return NullTime{sql.NullTime{Valid: false}}, nil
}
uTime, err := graphql.UnmarshalTime(t)
if err != nil {
return NullTime{}, err
}
return NullTime{
// @mrz: had to remove uTime.UnixMicro() > 0 in Valid (issue was golangci-lint typecheck)
sql.NullTime{
Time: uTime,
Valid: true,
},
}, err
}
// MarshalBSONValue method is called by bson.Marshal in Mongo for type = NullTime
func (x *NullTime) MarshalBSONValue() (bsontype.Type, []byte, error) {
if !x.Valid {
return bsontype.Null, nil, nil
}
valueType, b, err := bson.MarshalValue(x.Time)
return valueType, b, err
}
// UnmarshalBSONValue method is called by bson.Unmarshal in Mongo for type = NullTime
func (x *NullTime) UnmarshalBSONValue(t bsontype.Type, data []byte) error {
raw := bson.RawValue{Type: t, Value: data}
uTime := time.Time{}
if err := raw.Unmarshal(&uTime); err != nil {
return err
}
if raw.Value == nil {
x.Valid = false
return nil
}
x.Valid = true
x.Time = uTime
return nil
}
// MarshalJSON method is called by the JSON marshaller
func (x *NullTime) MarshalJSON() ([]byte, error) {
if !x.Valid {
return []byte("null"), nil
}
b, err := json.Marshal(x.Time)
return b, err
}
// UnmarshalJSON method is called by the JSON unmarshaller
func (x *NullTime) UnmarshalJSON(data []byte) error {
x.Valid = false
if data == nil {
return nil
}
var timeString string
if err := json.Unmarshal(data, &timeString); err != nil {
return err
}
if timeString == "" {
return nil
}
uTime, err := time.Parse(time.RFC3339, timeString)
if err != nil {
return err
}
x.Valid = true
x.Time = uTime
return nil
}