69 lines
1.4 KiB
Go
69 lines
1.4 KiB
Go
package streaming
|
|
|
|
import "encoding/json"
|
|
|
|
type EventType int8
|
|
|
|
const (
|
|
// Sent when an error occurs
|
|
// Payload: {code:int, message:string}
|
|
EventTypeError EventType = 1
|
|
// 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
|
|
|
|
// Receive events
|
|
// Subscribe to a new event
|
|
EventTypeSubscribe EventType = 126
|
|
// Unsubscribe from an event
|
|
EventTypeUnsubscribe EventType = 127
|
|
)
|
|
|
|
func (et EventType) Valid() bool {
|
|
switch et {
|
|
case EventTypeError:
|
|
return true
|
|
case EventTypeEcho:
|
|
return true
|
|
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
|
|
}
|