Skip to content

Commit 580aa21

Browse files
committed
refactor(activity): usa firstOrCreate em ReactWith conforme revisão do #561
Substitui o where()+first()/create() manual por firstOrCreate(), evitando a race entre o SELECT e o INSERT ao criar a primeira reação — sugestão do review do Clintonrocha98 na PR.
1 parent 6e5633a commit 580aa21

1 file changed

Lines changed: 9 additions & 13 deletions

File tree

‎app-modules/activity/src/Reaction/Actions/ReactWith.php‎

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -14,28 +14,24 @@
1414
public function handle(ReactWithDTO $dto): ?TimelineReaction
1515
{
1616
return DB::transaction(static function () use ($dto): ?TimelineReaction {
17-
$existing = UserReaction::query()
18-
->where('user_id', $dto->userId)
19-
->where('timeline_id', $dto->timelineId)
20-
->first();
21-
22-
if ($existing === null) {
23-
UserReaction::query()->create([
17+
$reaction = UserReaction::query()->firstOrCreate(
18+
[
2419
'user_id' => $dto->userId,
2520
'timeline_id' => $dto->timelineId,
26-
'reaction' => $dto->reaction,
27-
]);
28-
21+
],
22+
['reaction' => $dto->reaction],
23+
);
24+
if ($reaction->wasRecentlyCreated) {
2925
return $dto->reaction;
3026
}
3127

32-
if ($existing->reaction === $dto->reaction) {
33-
$existing->delete();
28+
if ($reaction->reaction === $dto->reaction) {
29+
$reaction->delete();
3430

3531
return null;
3632
}
3733

38-
$existing->update(['reaction' => $dto->reaction]);
34+
$reaction->update(['reaction' => $dto->reaction]);
3935

4036
return $dto->reaction;
4137
});

0 commit comments

Comments
 (0)