msgFromJson<T extends BaseMessage> static method

T? msgFromJson<T extends BaseMessage>(
  1. Map<String, dynamic> json, {
  2. ChannelType? channelType,
  3. String? type,
})

Implementation

static T? msgFromJson<T extends BaseMessage>(
  Map<String, dynamic> json, {
  ChannelType? channelType,
  String? type,
}) {
  final cmd = type ?? json['type'] as String;
  T msg;
  //basemessage backward compatibility -
  if (json['custom'] != null) json['data'] = json['custom'];
  if (json['ts'] != null) json['created_at'] = json['ts'];
  if (json['msg_id'] != null) json['message_id'] = json['msg_id'];
  if (json['req_id'] != null) json['request_id'] = json['req_id'];

  //manually insert type if channel is provided
  if (channelType != null) json['channel_type'] = channelType.asString();
  //manually insert reply_to_channel
  if (json['reply_to_channel'] != null) {
    json['is_reply_to_channel'] = json['reply_to_channel'];
  }

  if (T == UserMessage || CommandString.isUserMessage(cmd)) {
    msg = UserMessage.fromJson(json) as T;
  } else if (T == FileMessage || CommandString.isFileMessage(cmd)) {
    msg = FileMessage.fromJson(json) as T;
  } else if (T == AdminMessage || CommandString.isAdminMessage(cmd)) {
    msg = AdminMessage.fromJson(json) as T;
  } else {
    return null;
  }

  final metaArray = json['metaarray'];
  final metaArrayKeys = List<String>.from(json['metaarray_key_order'] ?? []);
  // NOTE: sorted_metaarray is from API, metaarray list is local,
  // metaarray map is from Web, so had to handle separately

  //local cmd case
  if (metaArray is List) {
    msg.metaArrays = metaArray
        .map((e) => MessageMetaArray.fromJson(e as Map<String, dynamic>))
        .toList();
  }
  //websocket cmd result case
  else if (metaArray is Map && metaArrayKeys.isNotEmpty) {
    msg.metaArrays = metaArrayKeys.map((e) {
      final value = List<String>.from(metaArray[e]);
      return MessageMetaArray(key: e, value: value);
    }).toList();
  }

  return msg;
}