route method

bool route(
  1. WebSocketMessage message
)

Tries to route message to a registered topic.

Returns true if the message was a topic envelope and was routed.

Implementation

bool route(WebSocketMessage message) {
  Map<String, dynamic>? envelope;

  final data = message.data;
  if (data is String) {
    try {
      final decoded = jsonDecode(data);
      if (decoded is Map<String, dynamic>) envelope = decoded;
    } catch (_) {
      return false;
    }
  } else if (data is Map<String, dynamic>) {
    envelope = data;
  }

  if (envelope == null) return false;
  final topicName = envelope[_kTopic] as String?;
  if (topicName == null) return false;

  final topic = _topics[topicName];
  if (topic == null) return false;

  final event = envelope[_kEvent] as String? ?? 'message';
  final payload = envelope[_kPayload];

  topic.push(WebSocketMessage(
    data: payload,
    timestamp: DateTime.now(),
    type: event,
    metadata: {_kTopic: topicName, _kEvent: event},
  ));
  return true;
}