sendMessage method

Future<SendMessageResponse> sendMessage (
  1. Message message
)

Send a message to this channel

Implementation

Future<SendMessageResponse> sendMessage(Message message) async {
  final messageId = message.id ?? Uuid().v4();
  final newMessage = message.copyWith(
    createdAt: message.createdAt ?? DateTime.now(),
    user: _client.state.user,
    id: messageId,
    status: MessageSendingStatus.SENDING,
  );

  if (message.parentId != null && message.id == null) {
    final parentMessage =
        state.messages.firstWhere((m) => m.id == message.parentId);

    state?.addMessage(parentMessage.copyWith(
      replyCount: parentMessage.replyCount + 1,
    ));
  }

  state?.addMessage(newMessage);

  try {
    final response = await _client.post(
      '$_channelURL/message',
      data: {
        'message': message
            .copyWith(
              id: messageId,
            )
            .toJson()
      },
    );

    final res = _client.decode(response.data, SendMessageResponse.fromJson);

    state?.addMessage(res.message);

    return res;
  } catch (error) {
    state?.retryQueue?.add([newMessage]);
    rethrow;
  }
}