From 1368838d754e9b2bea3317589b9fc970523d3a6c Mon Sep 17 00:00:00 2001 From: nitram509 Date: Wed, 30 Nov 2022 08:43:38 +0100 Subject: [PATCH] add convenience method for time.Time conversion also introducing 'gocrest' library for simpler test code --- go.mod | 2 ++ go.sum | 2 ++ value.go | 6 ++++++ value_test.go | 22 ++++++++++++++++++++++ 4 files changed, 32 insertions(+) create mode 100644 go.sum create mode 100644 value_test.go diff --git a/go.mod b/go.mod index 049d681..f26b81d 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,5 @@ module github.com/norunners/vert go 1.16 + +require github.com/corbym/gocrest v1.0.5 diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..0020080 --- /dev/null +++ b/go.sum @@ -0,0 +1,2 @@ +github.com/corbym/gocrest v1.0.5 h1:6FUvLjKkKQ2hwMel8OKIZqN3slYEOHIFY9+lVaroFnU= +github.com/corbym/gocrest v1.0.5/go.mod h1:lF3xBPnOU5DYDpa/vUq63SMxUhd5UAwGgmA8Z2pJ/Tk= diff --git a/value.go b/value.go index 1bc3006..f639c41 100644 --- a/value.go +++ b/value.go @@ -6,6 +6,7 @@ package vert import ( "reflect" "syscall/js" + "time" ) var ( @@ -90,6 +91,11 @@ func valueOfMap(v reflect.Value) js.Value { // valueOfStruct returns a new object value. func valueOfStruct(v reflect.Value) js.Value { + if t, ok := v.Interface().(time.Time); ok { + // special case: Time, instantiates a new js Date object + dateConstructor := js.Global().Get("Date") + return dateConstructor.New(t.Format(time.RFC3339)) + } t := v.Type() s := object.New() n := v.NumField() diff --git a/value_test.go b/value_test.go new file mode 100644 index 0000000..663852e --- /dev/null +++ b/value_test.go @@ -0,0 +1,22 @@ +package vert + +import ( + "github.com/corbym/gocrest/is" + "github.com/corbym/gocrest/then" + "testing" + "time" +) + +const isoStringLength = len("yyyy-MM-ddThh:mm:ss") + +func TestValueOfTime(t *testing.T) { + now := time.Now() + + jsVal := ValueOf(now) + + // cut of the timezone information, because seconds precision is sufficient for this test + jsValIsoString := jsVal.Call("toISOString").String() + jsValIsoString = jsValIsoString[:isoStringLength] + + then.AssertThat(t, jsValIsoString, is.EqualTo(now.UTC().Format(time.RFC3339)[:isoStringLength])) +}