Skip to content

Commit

Permalink
PostSiteMapSpec
Browse files Browse the repository at this point in the history
  • Loading branch information
EdiWang committed May 7, 2024
1 parent 5488d3d commit ebc61e5
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 7 deletions.
25 changes: 25 additions & 0 deletions src/Moonglade.Data/Specifications/PostSiteMapSpec.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using Moonglade.Data.Entities;

namespace Moonglade.Data.Specifications;

public sealed class PostSiteMapSpec : Specification<PostEntity, PostSiteMapInfo>
{
public PostSiteMapSpec()
{
Query.Where(p => p.IsPublished && !p.IsDeleted);
Query.Select(p => new PostSiteMapInfo
{
Slug = p.Slug,
CreateTimeUtc = p.PubDateUtc.GetValueOrDefault(),
UpdateTimeUtc = p.LastModifiedUtc
});
Query.AsNoTracking();
}
}

public class PostSiteMapInfo
{
public string Slug { get; set; }
public DateTime CreateTimeUtc { get; set; }
public DateTime? UpdateTimeUtc { get; set; }
}
13 changes: 6 additions & 7 deletions src/Moonglade.Web/Middleware/SiteMapMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,18 +40,17 @@ private static async Task<string> GetSiteMapData(
writer.WriteStartElement("urlset", "http://www.sitemaps.org/schemas/sitemap/0.9");

// Posts
var spec = new PostByStatusSpec(PostStatus.Published);
var posts = await postRepo
.SelectAsync(spec, p => new Tuple<string, DateTime?, DateTime?>(p.Slug, p.PubDateUtc, p.LastModifiedUtc), ct);
var spec = new PostSiteMapSpec();
var posts = await postRepo.ListAsync(spec, ct);

foreach (var (slug, pubDateUtc, lastModifyUtc) in posts.OrderByDescending(p => p.Item2))
foreach (var item in posts.OrderByDescending(p => p.UpdateTimeUtc))
{
var pubDate = pubDateUtc.GetValueOrDefault();
var pubDate = item.CreateTimeUtc;

writer.WriteStartElement("url");
writer.WriteElementString("loc", $"{siteRootUrl}/post/{pubDate.Year}/{pubDate.Month}/{pubDate.Day}/{slug.ToLower()}");
writer.WriteElementString("loc", $"{siteRootUrl}/post/{pubDate.Year}/{pubDate.Month}/{pubDate.Day}/{item.Slug.ToLower()}");
writer.WriteElementString("lastmod", pubDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture));
writer.WriteElementString("changefreq", GetChangeFreq(pubDateUtc.GetValueOrDefault(), lastModifyUtc));
writer.WriteElementString("changefreq", GetChangeFreq(pubDate, item.UpdateTimeUtc));
await writer.WriteEndElementAsync();
}

Expand Down

0 comments on commit ebc61e5

Please sign in to comment.