parse static method

SocketPacket parse(
  1. dynamic raw, {
  2. int? maxMessageBytes,
})

Implementation

static SocketPacket parse(dynamic raw, {int? maxMessageBytes}) {
  String text;
  if (raw is String) {
    text = raw;
  } else if (raw is List<int>) {
    text = utf8.decode(raw);
  } else {
    throw const FormatException('Unsupported message type');
  }

  if (maxMessageBytes != null && text.length > maxMessageBytes) {
    throw PayloadTooLargeException('Message too large');
  }

  try {
    final map = jsonDecode(text);
    if (map is! Map<String, dynamic>) {
      throw const FormatException('Invalid JSON object');
    }
    return SocketPacket.fromMap(map);
  } catch (e) {
    if (e is FormatException || e is PayloadTooLargeException) rethrow;
    throw const FormatException('Invalid packet format');
  }
}