Back to "إضافة جزء من نظام التعليق 1 -إعداد قاعدة البيانات"

This is a viewer only at the moment see the article on how this works.

To update the preview hit Ctrl-Alt-R (or ⌘-Alt-R on Mac) or Enter to refresh. The Save icon lets you save the markdown file to disk

This is a preview from the server running through my markdig pipeline

Entity Framework

إضافة جزء من نظام التعليق 1 -إعداد قاعدة البيانات

Monday, 26 August 2024

المقدمة

أحد الجوانب الرئيسية لموقع مدوني مثل هذا هو نظام تعليقات..

إعداد قاعدة البيانات

كما هو الحال مع بقية الموقع أنا أستخدم Postgres للمدونات، أبدأ بـ I.;، أستخدم الأسئلة المتكررة لحفظ التعليقات، أستعمل .، أنا لا أحب هذا بشدة، أكره ,، لكنها تخرجنا من البوابة بنظام تعليق متسلسل، و أنا لا أملك '، وليس لدي الكثير من حركة المرور، وعليه فإن ذلك، '، ليس أمراً كبيراً،).، سأنتقل إلى نظام أكثر فعالية في المستقبل، .

سياق الـ EF

في النظام الحالي نستخدم 'Comment Closure' لتحديد العلاقات بين التعليقات - حتى أستطيع دعم التعليقات المليئة

classDiagram
    class CommentEntity {
        int Id
        CommentStatus Status
        string Author
        string? HtmlContent
        string Content
        DateTime CreatedAt
        int PostId
        int? ParentCommentId
    }

    class BlogPostEntity {
        int Id
        string Title
        string Content
        DateTime CreatedAt
    }

    class CommentClosure {
        int AncestorId
        int DescendantId
        int Depth
    }

    CommentEntity "1" --> "1" BlogPostEntity : belongs to
    CommentEntity "1" --> "0..1" CommentEntity : parent
    CommentEntity "0..*" --> "0..*" CommentClosure : Ancestors
    CommentEntity "0..*" --> "0..*" CommentClosure : Descendants
    CommentClosure "1" --> "1" CommentEntity : Ancestor
    CommentClosure "1" --> "1" CommentEntity : Descendant

    class CommentStatus {
        <<enum>>
        Pending
        Approved
        Rejected
        Deleted
    }

يمكنكم أن تروا هنا أن كل CommentEntity لديه PostId من أجل البريد هو ' مرتبطة بـ, و ParentCommentId للتعليق هو ' ملصق ( إذا كان هناك ). CommentClosure جدول يستخدم لحفظ العلاقات بين التعليقات.

خدمة التعليق

الـ CommentService هو المسؤول عن إدارة التعليقات. لديه أساليب للإضافة, الموافقةM SK2 رفضهMSC3 وحذف التعليقات . لديه أيضًا أساليب للحصول على تعليقات لpostMST5 والحصول على تعليق لتعليقM ST6

واجهتنا لهذه الخدمة تبدو مثل هذه

public interface ICommentService
{
    Task<string> Add( int postId, int? parentCommentId, string author, string content);
    Task<List<CommentEntity>> GetForPost(int blogPostId, int page = 1, int pageSize = 10, int? maxDepth = null, CommentStatus? status = null);
    Task<List<CommentEntity>> GetDescendants(int commentId, int maxDepth = 0);

     Task<CommentEntity> Get(int commentId);
    Task<List<CommentEntity>> GetAncestors(int commentId);
    Task Delete(int commentId);
    Task Reject(int commentId);
    Task Approve(int commentId);
}

الطريقة الإضافية

طريقة إضافتنا تلخص هيكل نظام التعليقات

في البداية يبدأ المعامل الجديد..;.. لتلك المعاملات غير المألوفة هي طريقة للتأكد من أن مجموعة من العمليات تتم معاملتها كوحدة واحدة من العمل.. ... إذا فشل أي من العمليات..

ومن ثم يقوم بتحليل نص الملاحظات من ماركدون إلى HTML باستخدام مكتبة ماركديج. هذه طريقة بسيطة لتسمح للمستخدمين بصيغة تعليقاتهم باستخدام ماركدون.

لاحقاً يخلق الكائن ويحفظه في قاعدة البيانات.

يتم القيام بذلك في خطواتين - أولاً يتم حفظ الملاحظة, ثم تم حفظ إغلاق الملاحظاتM SK2 هذا لأن الملاحظ يجب أن يتم حفظه لإنتاج الرمز , الذي يستخدم في الإغلاق

ومن ثم نقوم ببناء السلسلة الهرمية CommentClosures التي تحدد العلاقات بين الملاحظات.

أخيراً , نقوم بعملية الإتصال . إذا فشلت أي من العمليات | , | عملية الإتخاذ تم قلبها |.

 public async Task<string> Add(int postId, int? parentCommentId, string author, string content)
  {
      await using var transaction = await context.Database.BeginTransactionAsync();
      try
      {
         var html = Markdig.Markdown.ToHtml(content);
          // Create the new comment
          var newComment = new CommentEntity()
          {
              HtmlContent = html,
              Content = content,
              CreatedAt = DateTime.UtcNow,
              PostId = postId,
              Author = author,
              Status = CommentStatus.Pending,
              ParentCommentId = parentCommentId
          };
            
          context.Comments.Add(newComment);
          await context.SaveChangesAsync();
          logger.LogInformation("Saved comment to DB");// Save to generate the new comment's Id

          // Insert into CommentClosure table
          var commentClosures = new List<CommentClosure>();

          // Self-referencing closure entry
          commentClosures.Add(new CommentClosure
          {
              AncestorId = newComment.Id,
              DescendantId = newComment.Id,
              Depth = 0
          });

          // If there is a parent comment, insert the ancestor relationships
          if (parentCommentId.HasValue)
          {
              // Fetch all ancestors of the parent comment
              var parentAncestors = await context.CommentClosures
                  .Where(cc => cc.DescendantId == parentCommentId.Value)
                  .ToListAsync();

              // Add ancestor relationships for the new comment
              foreach (var ancestor in parentAncestors)
              {
                  commentClosures.Add(new CommentClosure
                  {
                      AncestorId = ancestor.AncestorId,
                      DescendantId = newComment.Id,
                      Depth = ancestor.Depth + 1
                  });
              }

              // Add a direct parent-child relationship
              commentClosures.Add(new CommentClosure
              {
                  AncestorId = parentCommentId.Value,
                  DescendantId = newComment.Id,
                  Depth = 1
              });
          }

          context.CommentClosures.AddRange(commentClosures);
          await context.SaveChangesAsync();
          logger.LogInformation("Saved comment closure to DB");

          // Commit transaction
          await transaction.CommitAsync();
          return html;
      }
      catch (Exception e)
      {
          // Rollback transaction in case of failure
          await transaction.RollbackAsync();
          logger.LogError(e, "Failed to save comment to DB");
      }

      return string.Empty;
  }

طريقة GetForPost

لن نغطي الأمر كله لكن Add و Get هي عمليات CRUD الرئيسية لهذا الخدمة.

كما ترون لدينا تغريدات بناء على تعليق المستوى الأعلى. لدينا أيضاً maxDepth پارامتر الذي يسمح لنا بحد عمق شجرة التعليق. هذا مفيد إذا أردنا فقط أن نظهر تعليقات المستوى الأعلى-M SK2 أو إذا أريد الحد عمق الشجرة لتطوير الأداءMSC3

وبشكل غير مألوف مع هذه المقاربة المتكررة نحتاج أن نطبق فلتر العمارة بعد أن نأخذ تعليقاتنا..,.. كما نستطيع.. '.. لا نفعل ذلك في البحث..

  public async Task<List<CommentEntity>> GetForPost(int blogPostId, int page = 1, int pageSize = 10, int? maxDepth = null, CommentStatus? status = null)
  {
      // Step 1: Query the top-level comments for the specified blog post
      var query = context.Comments
          .Where(c => c.PostId == blogPostId)
          .OrderByDescending(c => c.CreatedAt)
          .Skip((page - 1) * pageSize)
          .Take(pageSize);

      // Step 2: Filter by status if provided
      if (status.HasValue)
      {
          query = query.Where(c => c.Status == status.Value);
      }

      var topLevelComments = await query
          .Include(c => c.ParentComment)
          .Include(d=>d.Descendants)
          .ToListAsync();

      // Step 4: Filter descendants based on the maxDepth
      foreach (var comment in topLevelComments)
      {
          if (maxDepth != null)
          {
              FilterDescendantsByDepth(comment, 0, maxDepth.Value);
          }
      }

      return topLevelComments;
  }

// Recursive helper method to limit the descendants based on the specified depth
  private void FilterDescendantsByDepth(CommentEntity comment, int currentDepth, int maxDepth)
  {
      if (currentDepth >= maxDepth)
      {
          // If the max depth is reached or there are no descendants, stop recursion
          comment.Descendants = new List<CommentClosure>();  // Clear further descendants beyond maxDepth
          return;
      }

      foreach (var closure in comment.Descendants.ToList())  // Iterate over a copy to prevent modification during iteration
      {
          FilterDescendantsByDepth(closure.Descendant, currentDepth + 1, maxDepth);
      }
  }

في الختام

هذا نظام تعليق بسلسلة بسيطة يستخدم الاستبيانات المتكررة لتخزين العلاقات بين التعليقات. إنه' ليس النظام الأكثر كفاءةM SK2 لكنه ' بسيط و يعملMST4 في المستقبلMSC5 سأغطي جوانب الجزء الأمامي من هذا النظامMSV7 الكثير من HTMXMSR8 AlpineMSSK9jsMSL10 و Tailwind CSSMSP11

حتى ذلك الحين , لا تقلقوا على أن تترك تعليقاً أسفل

logo

© 2026 Scott Galloway — Unlicense — All content and source code on this site is free to use, copy, modify, and sell.