Skip to content

Commit

Permalink
Refactor category update logic in UpdatePostCommandHandler
Browse files Browse the repository at this point in the history
Moved category update logic from Handle method to new private
UpdateCats method. UpdateCats handles MySQL workaround by
deleting old post-category relationships and clearing the
PostCategory collection of PostEntity, then adds new
post-category relationships based on provided category IDs.
This refactor simplifies the Handle method and improves code
readability.
  • Loading branch information
EdiWang committed Nov 1, 2024
1 parent e3c6b27 commit 99abf41
Showing 1 changed file with 25 additions and 20 deletions.
45 changes: 25 additions & 20 deletions src/Moonglade.Core/PostFeature/UpdatePostCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -93,26 +93,7 @@ await _tagRepo.AddAsync(new()
}
}

// 3. update categories
if (_useMySqlWorkaround)
{
var oldpcs = await _pcRepository.AsQueryable().Where(pc => pc.PostId == post.Id)
.ToListAsync(cancellationToken: ct);
await _pcRepository.DeleteRangeAsync(oldpcs, ct);
}

post.PostCategory.Clear();
if (postEditModel.SelectedCatIds.Any())
{
foreach (var cid in postEditModel.SelectedCatIds)
{
post.PostCategory.Add(new()
{
PostId = post.Id,
CategoryId = cid
});
}
}
await UpdateCats(post, postEditModel.SelectedCatIds, ct);

await _postRepo.UpdateAsync(post, ct);

Expand Down Expand Up @@ -158,4 +139,28 @@ private void UpdatePostDetails(PostEntity post, PostEditModel postEditModel, Dat
post.IsOutdated = postEditModel.IsOutdated;
post.RouteLink = $"{post.PubDateUtc.GetValueOrDefault().ToString("yyyy/M/d", CultureInfo.InvariantCulture)}/{postEditModel.Slug}";
}

private async Task UpdateCats(PostEntity post, Guid[] catIds, CancellationToken ct)
{
// 3. update categories
if (_useMySqlWorkaround)
{
var oldpcs = await _pcRepository.AsQueryable().Where(pc => pc.PostId == post.Id)
.ToListAsync(cancellationToken: ct);
await _pcRepository.DeleteRangeAsync(oldpcs, ct);
}

post.PostCategory.Clear();
if (catIds.Any())
{
foreach (var cid in catIds)
{
post.PostCategory.Add(new()
{
PostId = post.Id,
CategoryId = cid
});
}
}
}
}

0 comments on commit 99abf41

Please sign in to comment.