~emersion/public-inbox

This thread contains a patchset. You're looking at the original emails, but you may wish to use the patch review UI. Review patch

[PATCH gqlclient] gqlclient: introduce a Time type

Details
Message ID
<20230210104506.267351-1-contact@emersion.fr>
DKIM signature
missing
Download raw message
Patch: +37 -1
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
Reply to thread Export thread (mbox)