|
| 1 | +package worker |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "syscall/js" |
| 6 | +) |
| 7 | + |
| 8 | +// NewTypeError creates a new type error |
| 9 | +func NewTypeError(expType, gotType js.Type) error { |
| 10 | + return fmt.Errorf("value type should be %q, but got %q", expType, gotType) |
| 11 | +} |
| 12 | + |
| 13 | +type ValueUnmarshaler interface { |
| 14 | + UnmarshalValue(js.Value) error |
| 15 | +} |
| 16 | + |
| 17 | +// Args is collection if function call arguments |
| 18 | +type Args []js.Value |
| 19 | + |
| 20 | +// BindIndex binds argument at specified index to passed value |
| 21 | +func (args Args) BindIndex(index int, dest interface{}) error { |
| 22 | + if len(args) <= index { |
| 23 | + return fmt.Errorf("function expects %d arguments, but %d were passed", index+1, len(args)) |
| 24 | + } |
| 25 | + |
| 26 | + return BindValue(args[index], dest) |
| 27 | +} |
| 28 | + |
| 29 | +// Bind binds passed JS arguments to Go values |
| 30 | +// |
| 31 | +// Function supports *int, *bool, *string and ValueUnmarshaler values. |
| 32 | +func (args Args) Bind(targets ...interface{}) error { |
| 33 | + if len(args) != len(targets) { |
| 34 | + return fmt.Errorf("function expects %d arguments, but %d were passed", len(targets), len(args)) |
| 35 | + } |
| 36 | + |
| 37 | + for i, arg := range args { |
| 38 | + if err := BindValue(arg, targets[i]); err != nil { |
| 39 | + return fmt.Errorf("invalid argument %d type: %s", err) |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + return nil |
| 44 | +} |
| 45 | + |
| 46 | +// BindValue binds JS value to specified target |
| 47 | +func BindValue(val js.Value, dest interface{}) error { |
| 48 | + valType := val.Type() |
| 49 | + switch v := dest.(type) { |
| 50 | + case *int: |
| 51 | + if valType != js.TypeNumber { |
| 52 | + return NewTypeError(js.TypeNumber, valType) |
| 53 | + } |
| 54 | + |
| 55 | + *v = val.Int() |
| 56 | + case *bool: |
| 57 | + if valType != js.TypeBoolean { |
| 58 | + return NewTypeError(js.TypeBoolean, valType) |
| 59 | + } |
| 60 | + |
| 61 | + *v = val.Bool() |
| 62 | + case *string: |
| 63 | + if valType != js.TypeString { |
| 64 | + return NewTypeError(js.TypeString, valType) |
| 65 | + } |
| 66 | + |
| 67 | + *v = val.String() |
| 68 | + case ValueUnmarshaler: |
| 69 | + return v.UnmarshalValue(val) |
| 70 | + default: |
| 71 | + return fmt.Errorf("BindValue: unsupported JS type %q", valType) |
| 72 | + } |
| 73 | + |
| 74 | + return nil |
| 75 | +} |
0 commit comments