~emersion/public-inbox

gqlclient: gqlclient: introduce a Time type v1 APPLIED

Simon Ser: 1
 gqlclient: introduce a Time type

 2 files changed, 37 insertions(+), 1 deletions(-)
Export patchset (mbox)
How do I use this?

Copy & paste the following snippet into your terminal to import this patchset into git:

curl -s https://lists.sr.ht/~emersion/public-inbox/patches/38873/mbox | git am -3
Learn more about email & git

[PATCH gqlclient] gqlclient: introduce a Time type Export this patch

A small struct wrapper around time.Time which correctly maps null
JSON values to the zero time. Additionally it uses the
time.RFC3339Nano format like gqlgen does.

I've considered using pointers but that'd force callers to
explicitly check for nil values instead of handling idiomatic zero
time values.
---
 cmd/gqlclientgen/main.go |  2 +-
 time.go                  | 36 ++++++++++++++++++++++++++++++++++++
 2 files changed, 37 insertions(+), 1 deletion(-)
 create mode 100644 time.go

diff --git a/cmd/gqlclientgen/main.go b/cmd/gqlclientgen/main.go
index b7a68ac0d5c5..a7a0d65dd7b6 100644
--- a/cmd/gqlclientgen/main.go
+++ b/cmd/gqlclientgen/main.go
@@ -79,7 +79,7 @@ func genType(schema *ast.Schema, t *ast.Type) jen.Code {
		gen = jen.String()
	// Convenience types
	case "Time":
		gen = jen.Qual("time", "Time")
		gen = jen.Qual(gqlclient, "Time")
	case "Map":
		gen = jen.Map(jen.String()).Interface()
	case "Upload":
diff --git a/time.go b/time.go
new file mode 100644
index 000000000000..a5ab8687ce3d
--- /dev/null
+++ b/time.go
@@ -0,0 +1,36 @@
package gqlclient

import (
	"encoding/json"
	"time"
)

const timeLayout = time.RFC3339Nano

type Time struct {
	time.Time
}

func (t Time) MarshalJSON() ([]byte, error) {
	var v interface{}
	if !t.IsZero() {
		v = t.Format(timeLayout)
	}
	return json.Marshal(v)
}

func (t *Time) UnmarshalJSON(b []byte) error {
	if string(b) == "null" {
		t.Time = time.Time{}
		return nil
	}

	var s string
	if err := json.Unmarshal(b, &s); err != nil {
		return err
	}

	var err error
	t.Time, err = time.Parse(timeLayout, s)
	return err
}
-- 
2.39.1