feat: initial commit
This commit is contained in:
54
reach/client/helper.go
Normal file
54
reach/client/helper.go
Normal file
@ -0,0 +1,54 @@
|
||||
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" json:"name"`
|
||||
Payload any `mapstructure:"payload" json:"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
|
||||
}
|
Reference in New Issue
Block a user