fix(blog): auto-generate slug when admin leaves it empty
Build and Deploy to Kubernetes / build-and-deploy (push) Has been cancelled
Build and Deploy to Kubernetes / build-and-deploy (push) Has been cancelled
Allow optional slug on create/update, generate from title with unique fallback, so BackOffice can publish posts without manual slug entry. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
+5
-3
@@ -1,3 +1,4 @@
|
||||
using CMSMicroservice.Application.Common;
|
||||
using CMSMicroservice.Application.Common.FileManager;
|
||||
using CMSMicroservice.Application.Common.Interfaces;
|
||||
using CMSMicroservice.Domain.Entities.Blog;
|
||||
@@ -32,12 +33,13 @@ public class CreateBlogPostCommandHandler : IRequestHandler<CreateBlogPostComman
|
||||
if (string.IsNullOrEmpty(currentUserId) || !long.TryParse(currentUserId, out var authorUserId))
|
||||
throw new UnauthorizedAccessException("کاربر احراز هویت نشده است");
|
||||
|
||||
var slug = BlogSlugHelper.ResolveForCreate(request.Slug, request.Title.Trim());
|
||||
slug = await BlogSlugHelper.EnsureUniquePostSlugAsync(_context, slug, cancellationToken: cancellationToken);
|
||||
|
||||
var post = new BlogPost
|
||||
{
|
||||
Title = request.Title.Trim(),
|
||||
Slug = string.IsNullOrWhiteSpace(request.Slug)
|
||||
? $"post-{Guid.NewGuid():N}".Substring(0, 20)
|
||||
: request.Slug.Trim().ToLower(),
|
||||
Slug = slug,
|
||||
Summary = request.Summary?.Trim(),
|
||||
HtmlContent = request.HtmlContent,
|
||||
FeaturedImagePath = request.FeaturedImagePath,
|
||||
|
||||
+2
-2
@@ -11,9 +11,9 @@ public class CreateBlogPostCommandValidator : AbstractValidator<CreateBlogPostCo
|
||||
.MaximumLength(200).WithMessage("عنوان نمیتواند بیشتر از 200 کاراکتر باشد");
|
||||
|
||||
RuleFor(x => x.Slug)
|
||||
.NotEmpty().WithMessage("نشانی یکتا (slug) الزامی است")
|
||||
.MaximumLength(200).WithMessage("نشانی نمیتواند بیشتر از 200 کاراکتر باشد")
|
||||
.Matches(@"^[a-z0-9\-]+$").WithMessage("نشانی فقط میتواند شامل حروف کوچک انگلیسی، اعداد و خط تیره باشد");
|
||||
.Matches(@"^[a-z0-9\-]+$").WithMessage("نشانی فقط میتواند شامل حروف کوچک انگلیسی، اعداد و خط تیره باشد")
|
||||
.When(x => !string.IsNullOrWhiteSpace(x.Slug));
|
||||
|
||||
RuleFor(x => x.Summary)
|
||||
.MaximumLength(500).WithMessage("خلاصه نمیتواند بیشتر از 500 کاراکتر باشد")
|
||||
|
||||
+15
-2
@@ -1,3 +1,4 @@
|
||||
using CMSMicroservice.Application.Common;
|
||||
using CMSMicroservice.Application.Common.FileManager;
|
||||
using CMSMicroservice.Application.Common.Interfaces;
|
||||
using CMSMicroservice.Domain.Entities.Blog;
|
||||
@@ -29,9 +30,21 @@ public class UpdateBlogPostCommandHandler : IRequestHandler<UpdateBlogPostComman
|
||||
?? throw new KeyNotFoundException($"مقاله با شناسه {request.Id} یافت نشد");
|
||||
|
||||
post.Title = request.Title.Trim();
|
||||
// حفظ slug قبلی اگر مقدار جدید خالی باشد
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(request.Slug))
|
||||
post.Slug = request.Slug.Trim().ToLower();
|
||||
{
|
||||
post.Slug = await BlogSlugHelper.EnsureUniquePostSlugAsync(
|
||||
_context,
|
||||
BlogSlugHelper.NormalizeOptional(request.Slug)!,
|
||||
post.Id,
|
||||
cancellationToken);
|
||||
}
|
||||
else if (string.IsNullOrWhiteSpace(post.Slug))
|
||||
{
|
||||
var slug = BlogSlugHelper.ResolveForCreate(null, post.Title);
|
||||
post.Slug = await BlogSlugHelper.EnsureUniquePostSlugAsync(
|
||||
_context, slug, post.Id, cancellationToken);
|
||||
}
|
||||
post.Summary = request.Summary?.Trim();
|
||||
post.HtmlContent = request.HtmlContent;
|
||||
post.FeaturedImagePath = request.FeaturedImagePath;
|
||||
|
||||
+2
-2
@@ -13,9 +13,9 @@ public class UpdateBlogPostCommandValidator : AbstractValidator<UpdateBlogPostCo
|
||||
.MaximumLength(200).WithMessage("عنوان نمیتواند بیشتر از 200 کاراکتر باشد");
|
||||
|
||||
RuleFor(x => x.Slug)
|
||||
.NotEmpty().WithMessage("نشانی یکتا (slug) الزامی است")
|
||||
.MaximumLength(200).WithMessage("نشانی نمیتواند بیشتر از 200 کاراکتر باشد")
|
||||
.Matches(@"^[a-z0-9\-]+$").WithMessage("نشانی فقط میتواند شامل حروف کوچک انگلیسی، اعداد و خط تیره باشد");
|
||||
.Matches(@"^[a-z0-9\-]+$").WithMessage("نشانی فقط میتواند شامل حروف کوچک انگلیسی، اعداد و خط تیره باشد")
|
||||
.When(x => !string.IsNullOrWhiteSpace(x.Slug));
|
||||
|
||||
RuleFor(x => x.HtmlContent)
|
||||
.NotEmpty().WithMessage("محتوای مقاله الزامی است");
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
using CMSMicroservice.Application.Common.Interfaces;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace CMSMicroservice.Application.Common;
|
||||
|
||||
public static class BlogSlugHelper
|
||||
{
|
||||
private const int MaxSlugLength = 200;
|
||||
|
||||
public static string? NormalizeOptional(string? slug)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(slug))
|
||||
return null;
|
||||
|
||||
return slug.Trim().ToLowerInvariant();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds a URL slug from title (ASCII letters/digits). Persian-only titles yield empty string.
|
||||
/// </summary>
|
||||
public static string GenerateFromTitle(string title)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(title))
|
||||
return string.Empty;
|
||||
|
||||
var sb = new System.Text.StringBuilder();
|
||||
var lastWasHyphen = false;
|
||||
|
||||
foreach (var c in title.Trim().ToLowerInvariant())
|
||||
{
|
||||
if (c is >= 'a' and <= 'z' or >= '0' and <= '9')
|
||||
{
|
||||
sb.Append(c);
|
||||
lastWasHyphen = false;
|
||||
}
|
||||
else if (c is ' ' or '_' or '-')
|
||||
{
|
||||
if (sb.Length > 0 && !lastWasHyphen)
|
||||
{
|
||||
sb.Append('-');
|
||||
lastWasHyphen = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var result = sb.ToString().Trim('-');
|
||||
return result.Length > MaxSlugLength ? result[..MaxSlugLength].TrimEnd('-') : result;
|
||||
}
|
||||
|
||||
public static string CreateFallbackSlug() =>
|
||||
$"post-{Guid.NewGuid():N}"[..Math.Min(20, MaxSlugLength)];
|
||||
|
||||
public static string ResolveForCreate(string? requestedSlug, string title)
|
||||
{
|
||||
var normalized = NormalizeOptional(requestedSlug);
|
||||
if (!string.IsNullOrEmpty(normalized))
|
||||
return normalized;
|
||||
|
||||
var fromTitle = GenerateFromTitle(title);
|
||||
return !string.IsNullOrEmpty(fromTitle) ? fromTitle : CreateFallbackSlug();
|
||||
}
|
||||
|
||||
public static async Task<string> EnsureUniquePostSlugAsync(
|
||||
IApplicationDbContext context,
|
||||
string slug,
|
||||
long? excludePostId = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var candidate = slug;
|
||||
var suffix = 2;
|
||||
|
||||
while (await context.BlogPosts.AnyAsync(
|
||||
p => p.Slug == candidate && !p.IsDeleted && (excludePostId == null || p.Id != excludePostId.Value),
|
||||
cancellationToken))
|
||||
{
|
||||
var suffixStr = $"-{suffix}";
|
||||
var maxBase = MaxSlugLength - suffixStr.Length;
|
||||
var basePart = slug.Length > maxBase ? slug[..maxBase].TrimEnd('-') : slug;
|
||||
candidate = basePart + suffixStr;
|
||||
suffix++;
|
||||
}
|
||||
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user