|
5 | 5 | "fmt"
|
6 | 6 | "reflect"
|
7 | 7 | "syscall/js"
|
| 8 | + "time" |
8 | 9 | )
|
9 | 10 |
|
10 | 11 | // 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 {
|
123 | 124 | if isArray(x) {
|
124 | 125 | return decodeArray(x, v)
|
125 | 126 | }
|
| 127 | + if isDate(x) { |
| 128 | + return decodeDate(x, v) |
| 129 | + } |
126 | 130 | return decodeObject(x, v)
|
127 | 131 | case js.TypeFunction:
|
128 | 132 | return decodeFunction(x, v)
|
@@ -204,6 +208,17 @@ func decodeArray(x js.Value, v reflect.Value) error {
|
204 | 208 | return nil
|
205 | 209 | }
|
206 | 210 |
|
| 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 | + |
207 | 222 | // decodeObject decodes a JS object into the provided reflect.Value.
|
208 | 223 | func decodeObject(x js.Value, v reflect.Value) error {
|
209 | 224 | switch v.Kind() {
|
@@ -424,6 +439,16 @@ func isArray(x js.Value) bool {
|
424 | 439 | return arr.Call("isArray", x).Bool()
|
425 | 440 | }
|
426 | 441 |
|
| 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 | + |
427 | 452 | // initializePointerIfNil checks if the pointer is nil and initializes it as necessary.
|
428 | 453 | func initializePointerIfNil(v reflect.Value) {
|
429 | 454 | if v.Kind() != reflect.Ptr {
|
|
0 commit comments