changed subscription.Message.Data to []byte and added client.Send(m) helper
This commit is contained in:
@@ -9,7 +9,7 @@ import (
|
||||
// Message defines a client's channel data.
|
||||
type Message struct {
|
||||
Name string
|
||||
Data string
|
||||
Data []byte
|
||||
}
|
||||
|
||||
// Client is an interface for a generic subscription client.
|
||||
@@ -50,6 +50,9 @@ type Client interface {
|
||||
// IsDiscarded indicates whether the client has been "discarded"
|
||||
// and should no longer be used.
|
||||
IsDiscarded() bool
|
||||
|
||||
// Send sends the specified message to the client's channel (if not discarded).
|
||||
Send(m Message)
|
||||
}
|
||||
|
||||
// ensures that DefaultClient satisfies the Client interface
|
||||
@@ -183,3 +186,12 @@ func (c *DefaultClient) IsDiscarded() bool {
|
||||
|
||||
return c.isDiscarded
|
||||
}
|
||||
|
||||
// Send sends the specified message to the client's channel (if not discarded).
|
||||
func (c *DefaultClient) Send(m Message) {
|
||||
if c.IsDiscarded() {
|
||||
return
|
||||
}
|
||||
|
||||
c.Channel() <- m
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package subscriptions_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/pocketbase/pocketbase/tools/subscriptions"
|
||||
)
|
||||
@@ -143,3 +144,45 @@ func TestDiscard(t *testing.T) {
|
||||
t.Fatal("Expected true, got false")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSend(t *testing.T) {
|
||||
c := subscriptions.NewDefaultClient()
|
||||
|
||||
received := []string{}
|
||||
go func() {
|
||||
for {
|
||||
select {
|
||||
case m, ok := <-c.Channel():
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
received = append(received, m.Name)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
c.Send(subscriptions.Message{Name: "m1"})
|
||||
c.Send(subscriptions.Message{Name: "m2"})
|
||||
c.Discard()
|
||||
c.Send(subscriptions.Message{Name: "m3"})
|
||||
c.Send(subscriptions.Message{Name: "m4"})
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
|
||||
expected := []string{"m1", "m2"}
|
||||
|
||||
if len(received) != len(expected) {
|
||||
t.Fatalf("Expected %d messages, got %d", len(expected), len(received))
|
||||
}
|
||||
for _, name := range expected {
|
||||
var exists bool
|
||||
for _, n := range received {
|
||||
if n == name {
|
||||
exists = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !exists {
|
||||
t.Fatalf("Missing expected %q message, got %v", name, received)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user