Skip to content

Commit

Permalink
Get only 10 most recent posts in RSS
Browse files Browse the repository at this point in the history
  • Loading branch information
mashedkeyboard committed Oct 28, 2023
1 parent ea52c33 commit d34ebc8
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
13 changes: 12 additions & 1 deletion src/lib/blog/PostManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,17 @@ export async function getTaggedPosts(tag: string): Promise<PostMetadata[]> {
return await loadPosts().then((posts) => new Promise((res, rej) => posts.tags[tag] ? res(postsToMeta(posts.tags[tag])) : rej('No such tag')));
}

/**
* Sorts posts by their sort order.
*
* @export
* @param {Post[]} posts an array of posts
* @return {Post[]} the same array sorted
*/
export function sortPosts(posts: Post[]) {
return posts.sort((p1, p2) => p2.getSortOrder() - p1.getSortOrder());
}

/**
* postsToMeta takes an array of {@link Post}s and
* turns them into metadata for those posts.
Expand All @@ -89,5 +100,5 @@ export async function getTaggedPosts(tag: string): Promise<PostMetadata[]> {
* @return {PostMetadata[]} the corresponding metadata
*/
function postsToMeta(posts: Post[]): PostMetadata[] {
return posts.sort((p1, p2) => p2.getSortOrder() - p1.getSortOrder()).map((post) => post.getMetadata());
return sortPosts(posts).map((post) => post.getMetadata());
}
6 changes: 3 additions & 3 deletions src/routes/blog/rss.xml/+server.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { loadPosts } from "$lib/blog/PostManager";
import { loadPosts, sortPosts } from "$lib/blog/PostManager";
import { blogTitle } from "$lib/blog/Settings";
import { urlFor, urlForPost } from "$lib/Helpers";

Expand All @@ -9,7 +9,7 @@ export async function GET({ fetch }) {
// not ever running live.
// Design inspired by https://www.davidwparker.com/posts/how-to-make-an-rss-feed-in-sveltekit

const posts = await loadPosts();
const posts = sortPosts(Object.values((await loadPosts()).slugs));

const feed = `<?xml version="1.0" encoding="utf-8" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
Expand All @@ -20,7 +20,7 @@ export async function GET({ fetch }) {
<lastBuildDate>${(new Date()).toUTCString()}</lastBuildDate>
<link>${urlFor('/blog')}</link>
<ttl>60</ttl>
${(await Promise.all(Object.values(posts.slugs).map(async (post) => {
${(await Promise.all(posts.slice(0, 10).map(async (post) => {
let enclosure = '';
const url = urlForPost(post);
const image = post.getImage();
Expand Down

0 comments on commit d34ebc8

Please sign in to comment.