Skip to content

Commit 0eee403

Browse files
committed
add time.Time support
1 parent 915550b commit 0eee403

File tree

2 files changed

+33
-5
lines changed

2 files changed

+33
-5
lines changed

wasm/reflect_from.go

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"fmt"
66
"reflect"
77
"syscall/js"
8+
"time"
89
)
910

1011
// ErrMultipleReturnValue is an error where a JS function is attempted to be unmarshalled into a Go function with
@@ -123,6 +124,9 @@ func decodeValue(x js.Value, v reflect.Value) error {
123124
if isArray(x) {
124125
return decodeArray(x, v)
125126
}
127+
if isDate(x) {
128+
return decodeDate(x, v)
129+
}
126130
return decodeObject(x, v)
127131
case js.TypeFunction:
128132
return decodeFunction(x, v)
@@ -204,6 +208,17 @@ func decodeArray(x js.Value, v reflect.Value) error {
204208
return nil
205209
}
206210

211+
// decodeDate decodes a JS date into the provided reflect.Value.
212+
func decodeDate(x js.Value, v reflect.Value) error {
213+
t, ok := v.Addr().Interface().(*time.Time)
214+
if !ok {
215+
return InvalidTypeError{js.TypeObject, v.Type()}
216+
}
217+
millis := x.Call("getTime").Int()
218+
*t = time.UnixMilli(int64(millis))
219+
return nil
220+
}
221+
207222
// decodeObject decodes a JS object into the provided reflect.Value.
208223
func decodeObject(x js.Value, v reflect.Value) error {
209224
switch v.Kind() {
@@ -424,6 +439,16 @@ func isArray(x js.Value) bool {
424439
return arr.Call("isArray", x).Bool()
425440
}
426441

442+
// isDate uses x instanceof Date to check if the provided js.Value is a Date.
443+
func isDate(x js.Value) bool {
444+
date, err := Global().Get("Date")
445+
if err != nil {
446+
panic("Date not found")
447+
}
448+
449+
return x.InstanceOf(date)
450+
}
451+
427452
// initializePointerIfNil checks if the pointer is nil and initializes it as necessary.
428453
func initializePointerIfNil(v reflect.Value) {
429454
if v.Kind() != reflect.Ptr {

wasm/reflect_to.go

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"fmt"
55
"reflect"
66
"syscall/js"
7+
"time"
78
"unsafe"
89
)
910

@@ -52,6 +53,12 @@ func ToJSValue(x interface{}) js.Value {
5253
"real": real(x),
5354
"imag": imag(x),
5455
})
56+
case time.Time:
57+
date, err := Global().Get("Date")
58+
if err != nil {
59+
panic("Date constructor not found")
60+
}
61+
return date.New(x.Format(time.RFC3339))
5562
}
5663

5764
value := reflect.ValueOf(x)
@@ -113,11 +120,7 @@ func mapToJSObject(x reflect.Value) js.Value {
113120

114121
obj := objectConstructor.New()
115122
iter := x.MapRange()
116-
for {
117-
if !iter.Next() {
118-
break
119-
}
120-
123+
for iter.Next() {
121124
key := iter.Key()
122125
value := iter.Value().Interface()
123126
switch key := key.Interface().(type) {

0 commit comments

Comments
 (0)