69 lines
1.4 KiB
Go
69 lines
1.4 KiB
Go
package module
|
|
|
|
import (
|
|
"context"
|
|
|
|
"forge.cadoles.com/arcad/edge/pkg/app"
|
|
"forge.cadoles.com/arcad/edge/pkg/bus"
|
|
"github.com/dop251/goja"
|
|
"github.com/pkg/errors"
|
|
)
|
|
|
|
type NetModule struct {
|
|
backend *app.Backend
|
|
bus bus.Bus
|
|
}
|
|
|
|
func (m *NetModule) Name() string {
|
|
return "net"
|
|
}
|
|
|
|
func (m *NetModule) Export(export *goja.Object) {
|
|
if err := export.Set("broadcast", m.broadcast); err != nil {
|
|
panic(errors.Wrap(err, "could not set 'broadcast' function"))
|
|
}
|
|
|
|
if err := export.Set("send", m.send); err != nil {
|
|
panic(errors.Wrap(err, "could not set 'send' function"))
|
|
}
|
|
}
|
|
|
|
func (m *NetModule) broadcast(call goja.FunctionCall) goja.Value {
|
|
if len(call.Arguments) < 1 {
|
|
panic(m.backend.ToValue("invalid number of argument"))
|
|
}
|
|
|
|
data := call.Arguments[0].Export()
|
|
|
|
msg := NewBackendMessage(data)
|
|
if err := m.bus.Publish(context.Background(), msg); err != nil {
|
|
panic(errors.WithStack(err))
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (m *NetModule) send(call goja.FunctionCall) goja.Value {
|
|
if len(call.Arguments) < 1 {
|
|
panic(m.backend.ToValue("invalid number of argument"))
|
|
}
|
|
|
|
data := call.Arguments[0].Export()
|
|
|
|
msg := NewBackendMessage(data)
|
|
if err := m.bus.Publish(context.Background(), msg); err != nil {
|
|
panic(errors.WithStack(err))
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func NetModuleFactory(bus bus.Bus) app.BackendModuleFactory {
|
|
return func(backend *app.Backend) app.BackendModule {
|
|
return &NetModule{
|
|
backend: backend,
|
|
bus: bus,
|
|
}
|
|
}
|
|
}
|