Refactor realtime to realtime
This commit is contained in:
64
realtime.go
Normal file
64
realtime.go
Normal 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)
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user