diff --git a/src/routes/index.svelte b/src/routes/index.svelte index e92b4ff..eee2e5b 100644 --- a/src/routes/index.svelte +++ b/src/routes/index.svelte @@ -3,6 +3,8 @@ * @type {import('@sveltejs/kit').Load} */ export async function load({ fetch }) { + // Use a `limit` querystring parameter to fetch a limited number of posts + // e.g. fetch('posts.json?limit=5') for 5 most recent posts const posts = await fetch('/posts.json').then((res) => res.json()); return { diff --git a/src/routes/posts/index.json.js b/src/routes/posts/index.json.js index e9b8221..93f0bd5 100644 --- a/src/routes/posts/index.json.js +++ b/src/routes/posts/index.json.js @@ -1,10 +1,17 @@ import { slugFromPath } from '$lib/util'; /** @type {import('@sveltejs/kit').RequestHandler} */ -export async function get() { +export async function get({ query }) { const modules = import.meta.glob('./*.{md,svx,svelte.md}'); const postPromises = []; + const limit = Number(query.get('limit') ?? Infinity); + + if (Number.isNaN(limit)) { + return { + status: 400 + }; + } for (let [path, resolver] of Object.entries(modules)) { const slug = slugFromPath(path); @@ -17,11 +24,11 @@ export async function get() { } const posts = await Promise.all(postPromises); - const publishedPosts = posts.filter((post) => post.published); + const publishedPosts = posts.filter((post) => post.published).slice(0, limit); publishedPosts.sort((a, b) => (new Date(a.date) > new Date(b.date) ? -1 : 1)); return { - body: publishedPosts + body: publishedPosts.slice(0, limit) }; }