edge/pkg/module/util/assert.go

42 lines
931 B
Go
Raw Normal View History

2023-02-21 12:14:29 +01:00
package util
import (
"context"
"forge.cadoles.com/arcad/edge/pkg/app"
2023-02-21 12:14:29 +01:00
"github.com/dop251/goja"
"github.com/pkg/errors"
2023-02-21 12:14:29 +01:00
)
func AssertType[T any](v goja.Value, rt *goja.Runtime) T {
if c, ok := v.Export().(T); ok {
return c
}
2023-03-23 19:01:20 +01:00
panic(rt.ToValue(errors.Errorf("expected value to be a '%T', got '%T'", new(T), v.Export())))
2023-02-21 12:14:29 +01:00
}
func AssertContext(v goja.Value, r *goja.Runtime) context.Context {
return AssertType[context.Context](v, r)
}
func AssertObject(v goja.Value, r *goja.Runtime) map[string]any {
return AssertType[map[string]any](v, r)
}
func AssertString(v goja.Value, r *goja.Runtime) string {
return AssertType[string](v, r)
}
func AssertAppID(v goja.Value, r *goja.Runtime) app.ID {
value := v.Export()
switch typ := value.(type) {
case string:
return app.ID(typ)
case app.ID:
return typ
default:
panic(r.ToValue(errors.Errorf("expected value to be a string or app.ID, got '%T'", value)))
}
}