optimizations
This commit is contained in:
@@ -25,13 +25,21 @@ class SendMessageAction
|
||||
{
|
||||
$body = trim((string) ($payload['body'] ?? ''));
|
||||
$files = $payload['attachments'] ?? [];
|
||||
$clientTempId = $this->normalizedClientTempId($payload['client_temp_id'] ?? null);
|
||||
$created = false;
|
||||
|
||||
/** @var Message $message */
|
||||
$message = DB::transaction(function () use ($conversation, $sender, $payload, $body, $files) {
|
||||
$message = DB::transaction(function () use ($conversation, $sender, $payload, $body, $files, $clientTempId, &$created) {
|
||||
$existing = $this->findExistingMessage($conversation, $sender, $clientTempId);
|
||||
|
||||
if ($existing) {
|
||||
return $existing;
|
||||
}
|
||||
|
||||
$message = Message::query()->create([
|
||||
'conversation_id' => $conversation->id,
|
||||
'sender_id' => $sender->id,
|
||||
'client_temp_id' => $payload['client_temp_id'] ?? null,
|
||||
'client_temp_id' => $clientTempId,
|
||||
'message_type' => empty($files) ? 'text' : ($body === '' ? 'attachment' : 'text'),
|
||||
'body' => $body,
|
||||
'reply_to_message_id' => $payload['reply_to_message_id'] ?? null,
|
||||
@@ -48,9 +56,15 @@ class SendMessageAction
|
||||
'last_message_at' => $message->created_at,
|
||||
])->save();
|
||||
|
||||
$created = true;
|
||||
|
||||
return $message;
|
||||
});
|
||||
|
||||
if (! $created) {
|
||||
return $message->fresh(['sender:id,username,name', 'attachments', 'reactions']);
|
||||
}
|
||||
|
||||
$participantIds = $this->conversationState->activeParticipantIds($conversation);
|
||||
$this->conversationState->touchConversationCachesForUsers($participantIds);
|
||||
|
||||
@@ -68,6 +82,27 @@ class SendMessageAction
|
||||
return $message->fresh(['sender:id,username,name', 'attachments', 'reactions']);
|
||||
}
|
||||
|
||||
private function findExistingMessage(Conversation $conversation, User $sender, ?string $clientTempId): ?Message
|
||||
{
|
||||
if ($clientTempId === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return Message::query()
|
||||
->where('conversation_id', $conversation->id)
|
||||
->where('sender_id', $sender->id)
|
||||
->where('client_temp_id', $clientTempId)
|
||||
->whereNull('deleted_at')
|
||||
->first();
|
||||
}
|
||||
|
||||
private function normalizedClientTempId(mixed $value): ?string
|
||||
{
|
||||
$normalized = trim((string) $value);
|
||||
|
||||
return $normalized === '' ? null : $normalized;
|
||||
}
|
||||
|
||||
private function storeAttachment(UploadedFile $file, Message $message, int $userId): void
|
||||
{
|
||||
$mime = (string) $file->getMimeType();
|
||||
|
||||
Reference in New Issue
Block a user