added subscription.Message.WriteSSE method

This commit is contained in:
Gani Georgiev
2025-02-21 13:04:23 +02:00
parent 973916bb48
commit 4db497c5e1
6 changed files with 3481 additions and 3409 deletions
-6
View File
@@ -13,12 +13,6 @@ import (
const optionsParam = "options"
// Message defines a client's channel data.
type Message struct {
Name string `json:"name"`
Data []byte `json:"data"`
}
// SubscriptionOptions defines the request options (query params, headers, etc.)
// for a single subscription topic.
type SubscriptionOptions struct {
+37
View File
@@ -0,0 +1,37 @@
package subscriptions
import (
"io"
)
// Message defines a client's channel data.
type Message struct {
Name string `json:"name"`
Data []byte `json:"data"`
}
// WriteSSE writes the current message in a SSE format into the provided writer.
//
// For example, writing to a router.Event:
//
// m := Message{Name: "users/create", Data: []byte{...}}
// m.Write(e.Response, "yourEventId")
// e.Flush()
func (m *Message) WriteSSE(w io.Writer, eventId string) error {
parts := [][]byte{
[]byte("id:" + eventId + "\n"),
[]byte("event:" + m.Name + "\n"),
[]byte("data:"),
m.Data,
[]byte("\n\n"),
}
for _, part := range parts {
_, err := w.Write(part)
if err != nil {
return err
}
}
return nil
}
+25
View File
@@ -0,0 +1,25 @@
package subscriptions_test
import (
"strings"
"testing"
"github.com/pocketbase/pocketbase/tools/subscriptions"
)
func TestMessageWrite(t *testing.T) {
m := subscriptions.Message{
Name: "test_name",
Data: []byte("test_data"),
}
var sb strings.Builder
m.WriteSSE(&sb, "test_id")
expected := "id:test_id\nevent:test_name\ndata:test_data\n\n"
if v := sb.String(); v != expected {
t.Fatalf("Expected writer content\n%q\ngot\n%q", expected, v)
}
}