2023-10-15 17:08:55 +02:00
|
|
|
package streaming
|
|
|
|
|
|
|
|
import "encoding/json"
|
|
|
|
|
|
|
|
type EventType int8
|
|
|
|
|
|
|
|
const (
|
2023-10-15 21:39:50 +02:00
|
|
|
// Sent when an error occurs
|
|
|
|
// Payload: {code:int, message:string}
|
2023-10-15 17:08:55 +02:00
|
|
|
EventTypeError EventType = 1
|
2023-10-15 21:39:50 +02:00
|
|
|
// Sent when echoing back received messages
|
|
|
|
// Payload: <received message>
|
|
|
|
EventTypeEcho EventType = 2
|
|
|
|
// Sent on a new post being created
|
|
|
|
// Payload: <post object>
|
|
|
|
EventTypePost EventType = 3
|
2023-10-15 17:08:55 +02:00
|
|
|
|
2023-10-15 21:39:50 +02:00
|
|
|
// Receive events
|
|
|
|
// Subscribe to a new event
|
|
|
|
EventTypeSubscribe EventType = 126
|
|
|
|
// Unsubscribe from an event
|
2023-10-15 17:08:55 +02:00
|
|
|
EventTypeUnsubscribe EventType = 127
|
|
|
|
)
|
|
|
|
|
|
|
|
func (et EventType) Valid() bool {
|
|
|
|
switch et {
|
|
|
|
case EventTypeError:
|
|
|
|
return true
|
2023-10-15 21:39:50 +02:00
|
|
|
case EventTypeEcho:
|
|
|
|
return true
|
2023-10-15 17:08:55 +02:00
|
|
|
case EventTypePost:
|
|
|
|
return true
|
|
|
|
case EventTypeSubscribe:
|
|
|
|
return true
|
|
|
|
case EventTypeUnsubscribe:
|
|
|
|
return true
|
|
|
|
default:
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Returns true if this event can be subscribed to/unsubscribed from
|
|
|
|
func (et EventType) ValidReceive() bool {
|
|
|
|
if !et.Valid() {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
switch et {
|
|
|
|
case EventTypeError, EventTypeSubscribe, EventTypeUnsubscribe:
|
|
|
|
return false
|
|
|
|
default:
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
type Event struct {
|
|
|
|
Type EventType `json:"t"`
|
|
|
|
Data any `json:"d"`
|
|
|
|
}
|
|
|
|
|
|
|
|
type ErrorEvent struct {
|
|
|
|
Code int `json:"code"`
|
|
|
|
Message string `json:"message"`
|
|
|
|
}
|
|
|
|
|
|
|
|
type IncomingEvent struct {
|
|
|
|
Type EventType `json:"t"`
|
|
|
|
Data json.RawMessage `json:"d"` // this is a RawMessage so we can easily unmarshal it later
|
|
|
|
}
|