Skip to content

Commit e1863d6

Browse files
committed
send message and realtime in one request
1 parent 096c7b5 commit e1863d6

15 files changed

Lines changed: 87 additions & 87 deletions

File tree

MangoAPI.BusinessLogic/ApiCommands/Messages/SendMessageCommand.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
namespace MangoAPI.BusinessLogic.ApiCommands.Messages;
77

88
public record SendMessageCommand(
9+
Guid MessageId,
910
Guid UserId,
1011
Guid ChatId,
1112
string Text,

MangoAPI.BusinessLogic/ApiCommands/Messages/SendMessageCommandHandler.cs

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,14 @@
44
using System.Threading.Tasks;
55
using MangoAPI.Application.Interfaces;
66
using MangoAPI.Application.Services;
7+
using MangoAPI.BusinessLogic.HubConfig;
78
using MangoAPI.BusinessLogic.Models;
89
using MangoAPI.BusinessLogic.Responses;
910
using MangoAPI.Domain.Constants;
1011
using MangoAPI.Domain.Entities;
1112
using MangoAPI.Infrastructure.Database;
1213
using MediatR;
14+
using Microsoft.AspNetCore.SignalR;
1315
using Microsoft.EntityFrameworkCore;
1416

1517
namespace MangoAPI.BusinessLogic.ApiCommands.Messages;
@@ -21,17 +23,19 @@ public class SendMessageCommandHandler
2123
private readonly ResponseFactory<SendMessageResponse> responseFactory;
2224
private readonly IBlobServiceSettings blobServiceSettings;
2325
private readonly IBlobService blobService;
26+
private readonly IHubContext<ChatHub, IHubClient> hubContext;
2427

2528
public SendMessageCommandHandler(
2629
MangoDbContext dbContext,
2730
ResponseFactory<SendMessageResponse> responseFactory,
2831
IBlobServiceSettings blobServiceSettings,
29-
IBlobService blobService)
32+
IBlobService blobService, IHubContext<ChatHub, IHubClient> hubContext)
3033
{
3134
this.dbContext = dbContext;
3235
this.responseFactory = responseFactory;
3336
this.blobServiceSettings = blobServiceSettings;
3437
this.blobService = blobService;
38+
this.hubContext = hubContext;
3539
}
3640

3741
public async Task<Result<SendMessageResponse>> Handle(
@@ -69,6 +73,7 @@ public async Task<Result<SendMessageResponse>> Handle(
6973
var attachmentUniqueFileName = await UploadAttachmentIfExistsAsync(request);
7074

7175
var messageEntity = MessageEntity.Create(
76+
request.MessageId,
7277
request.UserId,
7378
request.ChatId,
7479
request.Text,
@@ -92,15 +97,18 @@ public async Task<Result<SendMessageResponse>> Handle(
9297
var attachmentUrl = attachmentUniqueFileName == null
9398
? null
9499
: $"{blobServiceSettings.MangoBlobAccess}/{attachmentUniqueFileName}";
95-
100+
96101
var messageResultDto = messageEntity.ToMessage(
97102
user.DisplayName,
98103
user.Id,
99104
user.DisplayNameColour,
100105
authorPictureUrl,
101106
attachmentUrl);
102107

103-
return responseFactory.SuccessResponse(SendMessageResponse.FromSuccess(messageResultDto));
108+
await hubContext.Clients.Group(request.ChatId.ToString()).BroadcastMessageAsync(messageResultDto);
109+
110+
return responseFactory.SuccessResponse(SendMessageResponse.FromSuccess(messageEntity.Id, attachmentUrl,
111+
messageEntity.CreatedAt));
104112
}
105113

106114
private async Task<string> UploadAttachmentIfExistsAsync(SendMessageCommand request)

MangoAPI.BusinessLogic/ApiCommands/Messages/SendMessageRequest.cs

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,17 +6,14 @@ namespace MangoAPI.BusinessLogic.ApiCommands.Messages;
66

77
public class SendMessageRequest
88
{
9-
[DefaultValue("hello world")]
10-
public string Text { get; set; }
9+
[DefaultValue("hello world")] public string Text { get; set; }
1110

1211
[DefaultValue("a8747c37-c5ef-4a87-943c-3ee3ae0a2871")]
1312
public Guid ChatId { get; set; }
1413

15-
[DefaultValue("John Doe")]
16-
public string InReplyToUser { get; set; }
14+
[DefaultValue("John Doe")] public string InReplyToUser { get; set; }
1715

18-
[DefaultValue("Hello world!")]
19-
public string InReplyToText { get; set; }
16+
[DefaultValue("Hello world!")] public string InReplyToText { get; set; }
2017

2118
[DefaultValue("2021-08-01T00:00:00.0000000")]
2219
public DateTime? CreatedAt { get; set; }
Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,26 @@
1-
using MangoAPI.BusinessLogic.Models;
2-
using MangoAPI.BusinessLogic.Responses;
1+
using MangoAPI.BusinessLogic.Responses;
32
using MangoAPI.Domain.Constants;
3+
using System;
44

55
namespace MangoAPI.BusinessLogic.ApiCommands.Messages;
66

77
public record SendMessageResponse : ResponseBase
88
{
9-
public Message MessageModel { get; init; }
9+
public string AttachmentUrl { get; set; }
1010

11-
public static SendMessageResponse FromSuccess(Message messageModel)
11+
public Guid NewMessageId { get; set; }
12+
13+
public DateTime CreatedAt { get; set; }
14+
15+
public static SendMessageResponse FromSuccess(Guid newMessageId, string attachmentUrl, DateTime createdAt)
1216
{
1317
return new SendMessageResponse
1418
{
1519
Success = true,
1620
Message = ResponseMessageCodes.Success,
17-
MessageModel = messageModel,
21+
NewMessageId = newMessageId,
22+
AttachmentUrl = attachmentUrl,
23+
CreatedAt = createdAt
1824
};
1925
}
2026
}

MangoAPI.Client/src/app/components/chats/chats.component.ts

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@ import { SendMessageResponse } from '../../types/responses/SendMessageResponse';
2323
import { ReplyStateService } from 'src/app/services/states/replyState.service';
2424
import { Reply } from 'src/app/types/models/Reply';
2525
import { GetChatMessagesResponse } from '../../types/responses/GetChatMessagesResponse';
26-
import { RealtimeService } from '../../services/api/realtime.service';
2726
import { BaseResponse } from '../../types/responses/BaseResponse';
2827
import { GetUserChatsResponse } from '../../types/responses/GetUserChatsResponse';
2928
import { DeleteMessageResponse } from '../../types/responses/DeleteMessageResponse';
@@ -46,7 +45,7 @@ export class ChatsComponent implements OnInit {
4645
private _apiBaseService: ApiBaseService,
4746
public _modalWindowStateService: ModalWindowStateService,
4847
public _replyStateService: ReplyStateService,
49-
private _realtimeService: RealtimeService,
48+
// private _realtimeService: RealtimeService,
5049
private _defaultChatHelper: DefaultChatHelper
5150
) {}
5251

@@ -227,10 +226,12 @@ export class ChatsComponent implements OnInit {
227226
return;
228227
}
229228

229+
const messageId = crypto.randomUUID();
230230
const createdAt = new Date().toISOString();
231231
const sendMessageFormData = new FormData();
232232

233233
sendMessageFormData.append('text', newMessageText);
234+
sendMessageFormData.append('messageId', messageId);
234235
sendMessageFormData.append('chatId', this.activeChatId);
235236
sendMessageFormData.append('inReplyToUser', this._replyStateService.reply?.displayName ?? '');
236237
sendMessageFormData.append('inReplyToText', this._replyStateService.reply?.text ?? '');
@@ -240,6 +241,7 @@ export class ChatsComponent implements OnInit {
240241
}
241242

242243
const newMessage = new Message(
244+
messageId,
243245
tokens.userId,
244246
this.activeChatId,
245247
tokens.userDisplayName,
@@ -262,15 +264,17 @@ export class ChatsComponent implements OnInit {
262264

263265
const response = await firstValueFrom<SendMessageResponse>(sendMessage$);
264266

265-
newMessage.messageId = response.messageModel.messageId;
266-
newMessage.attachmentUrl = response.messageModel.attachmentUrl;
267-
newMessage.createdAt = response.messageModel.createdAt;
267+
console.log(JSON.stringify(response));
268268

269-
const sendNotification$ = this._realtimeService.sendRealtimeNewMessageNotification(
270-
response.messageModel
271-
);
269+
// newMessage.messageId = response.messageModel.messageId;
270+
newMessage.attachmentUrl = response.attachmentUrl;
271+
newMessage.createdAt = response.createdAt;
272272

273-
await firstValueFrom<BaseResponse>(sendNotification$);
273+
// const sendNotification$ = this._realtimeService.sendRealtimeNewMessageNotification(
274+
// response.messageModel
275+
// );
276+
//
277+
// await firstValueFrom<BaseResponse>(sendNotification$);
274278

275279
this.clearAttachmentInput();
276280
this.scrollToEnd();
@@ -401,6 +405,8 @@ export class ChatsComponent implements OnInit {
401405
}
402406

403407
private onMessageSendHandler(message: Message) {
408+
console.log(JSON.stringify(message));
409+
404410
message.self = message.userId == this.userId;
405411
const chat = this.chats.filter((x) => x.chatId === message.chatId)[0];
406412
chat.lastMessageAuthor = message.userDisplayName;
@@ -415,8 +421,6 @@ export class ChatsComponent implements OnInit {
415421
if (message.chatId === this.activeChatId && !includesMessage) {
416422
this.messages.push(message);
417423
}
418-
419-
this.scrollToEnd();
420424
}
421425

422426
private onMessageEditHandler(notification: EditMessageNotification) {

MangoAPI.Client/src/app/services/api/realtime.service.ts

Lines changed: 0 additions & 24 deletions
This file was deleted.

MangoAPI.Domain/Entities/MessageEntity.cs

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ public sealed class MessageEntity
3030
private MessageEntity()
3131
{
3232
}
33-
33+
3434
private MessageEntity(Guid userId, Guid chatId, string text)
3535
{
3636
Id = Guid.NewGuid();
@@ -58,7 +58,40 @@ private MessageEntity(
5858
new MessageEntityValidator().ValidateAndThrow(this);
5959
}
6060

61+
private MessageEntity(
62+
Guid id,
63+
Guid userId,
64+
Guid chatId,
65+
string text,
66+
string inReplyToUser,
67+
string inReplyToText,
68+
string attachmentFileName) : this(userId, chatId, text, inReplyToUser, inReplyToText, attachmentFileName)
69+
{
70+
Id = id;
71+
new MessageEntityValidator().ValidateAndThrow(this);
72+
}
73+
74+
public static MessageEntity Create(
75+
Guid userId,
76+
Guid chatId,
77+
string text,
78+
string inReplyToUser,
79+
string inReplyToText,
80+
string attachmentFileName)
81+
{
82+
var message = new MessageEntity(
83+
userId,
84+
chatId,
85+
text,
86+
inReplyToUser,
87+
inReplyToText,
88+
attachmentFileName);
89+
90+
return message;
91+
}
92+
6193
public static MessageEntity Create(
94+
Guid id,
6295
Guid userId,
6396
Guid chatId,
6497
string text,
@@ -67,6 +100,7 @@ public static MessageEntity Create(
67100
string attachmentFileName)
68101
{
69102
var message = new MessageEntity(
103+
id,
70104
userId,
71105
chatId,
72106
text,

MangoAPI.IntegrationTests/ApiCommandsTests/DeleteMessageCommandHandlerTests/DeleteMessageShouldThrowChatNotFound.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ await MangoModule.RequestAsync(
3131
var command = new DeleteMessageCommand(
3232
UserId: user.Response.Tokens.UserId,
3333
ChatId: Guid.NewGuid(),
34-
MessageId: message.Response.MessageModel.MessageId);
34+
MessageId: message.Response.NewMessageId);
3535

3636
var result = await MangoModule.RequestAsync(command, CancellationToken.None);
3737

MangoAPI.IntegrationTests/ApiCommandsTests/DeleteMessageCommandHandlerTests/DeleteMessageTestSuccess.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ await MangoModule.RequestAsync(
2727
var command = new DeleteMessageCommand(
2828
UserId: user.Response.Tokens.UserId,
2929
ChatId: chat.Response.ChatId,
30-
MessageId: message.Response.MessageModel.MessageId);
30+
MessageId: message.Response.NewMessageId);
3131

3232
var result = await MangoModule.RequestAsync(command, CancellationToken.None);
3333

MangoAPI.IntegrationTests/ApiCommandsTests/EditMessageCommandHandlerTests/EditMessageShouldThrowChatNotFound.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ public async Task EditMessageCommandHandlerTestShouldThrowChatNotFoundAsync()
3030
var command = new EditMessageCommand(
3131
ChatId: Guid.Empty,
3232
petroId,
33-
message.Response.MessageModel.MessageId,
33+
message.Response.NewMessageId,
3434
ModifiedText: "Message edited");
3535

3636
var result = await MangoModule.RequestAsync(command, CancellationToken.None);

0 commit comments

Comments
 (0)