Skip to content

Instantly share code, notes, and snippets.

@zackbloom
Created December 18, 2021 23:18
Show Gist options
  • Save zackbloom/d3e039fed92757b743e26ecf4e908c50 to your computer and use it in GitHub Desktop.
Save zackbloom/d3e039fed92757b743e26ecf4e908c50 to your computer and use it in GitHub Desktop.
package types
import (
"database/sql/driver"
"fmt"
"io"
"time"
)
type NullableTime struct {
time.Time
Valid bool
}
func (nt *NullableTime) Scan(value interface{}) error {
nt.Time, nt.Valid = value.(time.Time)
if nt.Time.IsZero() {
nt.Valid = false
}
return nil
}
func (nt NullableTime) Value() (driver.Value, error) {
if !nt.Valid || nt.IsZero() {
return nil, nil
}
return nt.Time, nil
}
func (nt NullableTime) MarshalJSON() ([]byte, error) {
if nt.Valid && !nt.Time.IsZero() {
return nt.Time.MarshalJSON()
} else {
return []byte("null"), nil
}
}
var FORMATS = []string{
`2006-01-02 15:04:05.999999999-07`,
`2006-01-02`,
time.RFC3339,
time.RFC3339Nano,
}
func (nt *NullableTime) UnmarshalJSON(data []byte) (err error) {
sData := string(data)
if sData == "null" {
*nt = NullableTime{time.Time{}, false}
return
}
var t time.Time
for _, format := range FORMATS {
t, err = time.Parse(`"`+format+`"`, sData)
if err == nil {
break
}
}
if err == nil {
*nt = NullableTime{t, true}
}
return
}
func (nt *NullableTime) UnmarshalGQL(v interface{}) error {
asString, ok := v.(string)
if !ok {
return fmt.Errorf("date must be a string")
}
return nt.UnmarshalJSON([]byte(asString))
}
func (nt NullableTime) MarshalGQL(w io.Writer) {
bytes, err := nt.MarshalJSON()
if err != nil {
panic(err)
}
w.Write(bytes)
}
func (nt NullableTime) ValueOrNil() *time.Time {
if nt.Valid {
return &nt.Time
} else {
return nil
}
}
func (nt NullableTime) Equal(date NullableTime) bool {
if !nt.Valid || !date.Valid {
return !nt.Valid && !date.Valid
}
return nt.Time.Equal(date.Time)
}
func NullableNow() NullableTime {
return NullableTime{
time.Now(),
true,
}
}
func NewNullableTime(date *time.Time) NullableTime {
if date == nil {
return NullableTime{
Valid: false,
}
} else {
return NullableTime{
Time: *date,
Valid: true,
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment