Refactor realtime to realtime

This commit is contained in:
2024-06-16 22:59:03 +02:00
parent f182fceafd
commit 369f8f2601
2 changed files with 78 additions and 22 deletions

64
realtime.go Normal file
View File

@@ -0,0 +1,64 @@
package main
import (
"bytes"
"encoding/json"
"log"
"net/http"
"github.com/r3labs/sse"
)
type RealtimeListener struct {
Url string
Collections []string
Chan chan string
client *sse.Client
}
type Subscription struct {
ClientId string `json:"clientId"`
Subscriptions []string `json:"subscriptions"`
}
func (listener RealtimeListener) handlePbConnect(msg *sse.Event) {
var connectEvent ConnectEvent
err := json.Unmarshal(msg.Data, &connectEvent)
if err != nil {
log.Printf("Error unmarshalling PB_CONNECT event: %v\n", err)
return
}
log.Printf("Client ID: %v\n", connectEvent.ClientId)
subscription := Subscription{
ClientId: connectEvent.ClientId,
Subscriptions: []string{"workshop_link"},
}
body, err := json.Marshal(subscription)
if err != nil {
log.Printf("Error marshalling subscription body: %v\n", err)
return
}
resp, err := http.Post(POCKETBASE_REALTIME, "application/json", bytes.NewBuffer(body))
if err != nil {
log.Printf("Error posting subscription: %v\n", err)
return
}
defer resp.Body.Close()
}
func (listener RealtimeListener) handlePbEvent(msg *sse.Event) {
log.Println(msg)
// listener.Chan <- msg.Data
}
func (listener RealtimeListener) initialize() {
listener.client = sse.NewClient(listener.Url)
listener.client.Subscribe("PB_CONNECT", listener.handlePbConnect)
for _, collection := range listener.Collections {
listener.client.Subscribe(collection, listener.handlePbEvent)
}
}