edge/pkg/module/net.go

69 lines
1.4 KiB
Go
Raw Normal View History

2023-02-09 12:16:36 +01:00
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.Server
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 := NewServerMessage(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 := NewServerMessage(data)
if err := m.bus.Publish(context.Background(), msg); err != nil {
panic(errors.WithStack(err))
}
return nil
}
func NetModuleFactory(bus bus.Bus) app.ServerModuleFactory {
return func(backend *app.Server) app.ServerModule {
return &NetModule{
backend: backend,
bus: bus,
}
}
}