Skip to content

Commit

Permalink
add limit querystring parameter
Browse files Browse the repository at this point in the history
  • Loading branch information
mvasigh committed May 15, 2021
1 parent 80e9630 commit 7d09f22
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
2 changes: 2 additions & 0 deletions src/routes/index.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
13 changes: 10 additions & 3 deletions src/routes/posts/index.json.js
Original file line number Diff line number Diff line change
@@ -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);
Expand All @@ -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)
};
}

0 comments on commit 7d09f22

Please sign in to comment.