Skip to content

Commit

Permalink
chore: split message and event
Browse files Browse the repository at this point in the history
  • Loading branch information
mathnogueira committed Apr 27, 2022
1 parent acc78c4 commit 868f1d6
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 11 deletions.
17 changes: 11 additions & 6 deletions server/go/websocket/messages.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,24 +7,29 @@ type Message struct {
Message interface{} `json:"message"`
}

type Event struct {
Type string `json:"type"`
Event interface{} `json:"event"`
}

func SuccessMessage(messageType string) Message {
return Message{
Type: messageType,
Message: "success",
}
}

func Error(err error) Message {
func ErrorMessage(err error) Message {
return Message{
Type: "error",
Message: err.Error(),
}
}

func UpdateMessage(object interface{}) Message {
jsonContent, _ := json.Marshal(object)
return Message{
Type: "update",
Message: jsonContent,
func ResourceUpdatedEvent(resource interface{}) Event {
jsonContent, _ := json.Marshal(resource)
return Event{
Type: "update",
Event: jsonContent,
}
}
4 changes: 2 additions & 2 deletions server/go/websocket/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,15 @@ func (r *Router) ListenAndServe(addr string) {
messageObject := routingMessage{}
err := json.Unmarshal(message, &messageObject)
if err != nil {
errMessage := Error(fmt.Errorf("could not unmarshal message: %w", err))
errMessage := ErrorMessage(fmt.Errorf("could not unmarshal message: %w", err))
conn.WriteJSON(errMessage)
return
}

if handler, exists := r.routes[messageObject.Type]; exists {
handler(conn, message)
} else {
conn.WriteJSON(Error(fmt.Errorf("No routes for message type %s", messageObject.Type)))
conn.WriteJSON(ErrorMessage(fmt.Errorf("No routes for message type %s", messageObject.Type)))
}
}

Expand Down
6 changes: 3 additions & 3 deletions server/go/websocket/subscribe.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,17 @@ func HandleSubscribeCommand(conn *websocket.Conn, message []byte) {
msg := subscriptionMessage{}
err := json.Unmarshal(message, &msg)
if err != nil {
conn.WriteJSON(Error(fmt.Errorf("invalid subscription message: %w", err)))
conn.WriteJSON(ErrorMessage(fmt.Errorf("invalid subscription message: %w", err)))
return
}

if msg.ResourceID == "" || msg.ResourceType == "" {
conn.WriteJSON(Error(fmt.Errorf("either ResourceType or ResourceID is empty")))
conn.WriteJSON(ErrorMessage(fmt.Errorf("either ResourceType or ResourceID is empty")))
return
}

messageConverter := subscription.NewSubscriberFunction(func(m *subscription.Message) error {
err := conn.WriteJSON(UpdateMessage(m.Content))
err := conn.WriteJSON(ResourceUpdatedEvent(m.Content))
if err != nil {
return fmt.Errorf("could not send update message: %w", err)
}
Expand Down

0 comments on commit 868f1d6

Please sign in to comment.