55 lines
1.1 KiB
Go
55 lines
1.1 KiB
Go
package client
|
|
|
|
import (
|
|
"context"
|
|
|
|
"github.com/mitchellh/mapstructure"
|
|
"github.com/pkg/errors"
|
|
)
|
|
|
|
func OnMessage[T any](ctx context.Context, client *Client, mType string) (chan T, error) {
|
|
ch := make(chan T)
|
|
|
|
rawChan, err := client.On(ctx, mType)
|
|
if err != nil {
|
|
return nil, errors.WithStack(err)
|
|
}
|
|
|
|
go func() {
|
|
defer close(ch)
|
|
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
|
|
case rawMsg := <-rawChan:
|
|
var msg T
|
|
if err := mapstructure.Decode(rawMsg, &msg); err != nil {
|
|
panic(errors.WithStack(err))
|
|
}
|
|
|
|
ch <- msg
|
|
}
|
|
}
|
|
}()
|
|
|
|
return ch, nil
|
|
}
|
|
|
|
// Broadcast is a broadcasted message containing module realtime informations.
|
|
type Broadcast struct {
|
|
Name string `mapstructure:"name"`
|
|
Payload map[string]interface{} `mapstructure:"payload"`
|
|
}
|
|
|
|
// OnBroadcast listens for ReachView "broadcast" messages
|
|
func OnBroadcast(ctx context.Context, client *Client) (chan Broadcast, error) {
|
|
ch, err := OnMessage[Broadcast](ctx, client, "broadcast")
|
|
if err != nil {
|
|
return nil, errors.WithStack(err)
|
|
}
|
|
|
|
return ch, nil
|
|
}
|