From f3e8755f4800ab854817f9d3c3469cccf306595d Mon Sep 17 00:00:00 2001 From: Demis Bellot Date: Wed, 3 Apr 2024 21:30:29 +0800 Subject: [PATCH] prevent duplicate titles --- MyApp.ServiceInterface/QuestionServices.cs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/MyApp.ServiceInterface/QuestionServices.cs b/MyApp.ServiceInterface/QuestionServices.cs index daf0b91..dad4f6d 100644 --- a/MyApp.ServiceInterface/QuestionServices.cs +++ b/MyApp.ServiceInterface/QuestionServices.cs @@ -48,22 +48,28 @@ public async Task Any(AskQuestion request) var userName = GetUserName(); var now = DateTime.UtcNow; - var postId = (int)appConfig.GetNextPostId(); + var postId = (int)appConfig.GetNextPostId(); + var title = request.Title.Trim(); + var body = request.Body.Trim(); var slug = request.Title.GenerateSlug(200); var summary = request.Body.StripHtml().SubstringWithEllipsis(0, 200); + + var existingPost = await Db.SingleAsync(Db.From().Where(x => x.Title == title)); + if (existingPost != null) + throw new ArgumentException($"Question with title '{title}' already used in question {existingPost.Id}", nameof(Post.Title)); Post createPost() => new() { Id = postId, PostTypeId = 1, - Title = request.Title, + Title = title, Tags = tags, Slug = slug, Summary = summary, CreationDate = now, CreatedBy = userName, LastActivityDate = now, - Body = request.Body, + Body = body, RefId = request.RefId, };