Files
messengerapi/code/MessengerApi/Handlers/Endpoint/SendEndpointHandler.cs
masiton a44912ac87
All checks were successful
Build and Push Docker Image / build (push) Successful in 55s
Build and Push Docker Image / docker (push) Successful in 36s
payloadLifespan/payloadLifetime and other name variants unified to Time To Live naming.
2025-07-05 17:07:53 +02:00

60 lines
2.0 KiB
C#

using MessengerApi.Configuration.Model;
using MessengerApi.Contracts.Models.Scoped;
using MessengerApi.Db.Entities;
using MessengerApi.Models.Scoped;
namespace MessengerApi.Handlers.Endpoint
{
public class SendEndpointHandler
{
private readonly MessengerConfiguration configuration;
private readonly ILogger logger;
private readonly Timing timing;
private readonly Identity identity;
private readonly IUnitOfWork unitOfWork;
public SendEndpointHandler(
MessengerConfiguration configuration,
ILogger logger,
IUnitOfWork unitOfWork,
Timing timing,
Identity identity)
{
this.configuration = configuration;
this.logger = logger;
this.unitOfWork = unitOfWork;
this.timing = timing;
this.identity = identity;
}
public Task<Message> SendMessage(
Guid? toUserId,
string payload,
string payloadType,
int? timeToLiveInSeconds)
{
// Authorize.
var targetRecipientId = toUserId.HasValue
? this.identity.UserRoutes.Single(x => x.From.Id == this.identity.User.Id && x.To.Id == toUserId.Value).To.Id
: this.identity.UserRoutes.Single().To.Id;
this.logger.Debug($"[{this.timing.Timestamp:s}] User {this.identity.User.Name} is authorized to send message to {targetRecipientId}.");
// Act.
var message = new Message
{
Id = Guid.NewGuid(),
CreatedUtc = this.timing.Timestamp,
FromId = this.identity.User.Id,
ToId = targetRecipientId,
Payload = payload,
PayloadType = payloadType,
TimeToLiveInSeconds = timeToLiveInSeconds ?? (this.configuration.DefaultMessageTimeToLiveInSeconds)
};
this.unitOfWork.Messages.Add(message);
return Task.FromResult(message);
}
}
}