78 lines
2.2 KiB
TypeScript
78 lines
2.2 KiB
TypeScript
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
|
|
import { createExcerpt } from '$lib/markdown/excerpt';
|
|
import type { PageServerLoad } from './$types';
|
|
|
|
export const load: PageServerLoad = async ({ platform }) => {
|
|
const db = platform?.env?.DB;
|
|
|
|
if (!db) {
|
|
// Fallback data if DB is not available (e.g. during dev without wrangler, or missing bindings)
|
|
return {
|
|
posts: [
|
|
{
|
|
id: 1,
|
|
title: 'Hello, BlogFlare! (Fallback)',
|
|
excerpt:
|
|
'This is my first post on BlogFlare. Welcome to my new blog powered by SvelteKit.',
|
|
date: 'Jul 12, 2026',
|
|
slug: 'hello-world',
|
|
cover: null
|
|
},
|
|
{
|
|
id: 2,
|
|
title: 'The Beauty of Typecho Theme VOID',
|
|
excerpt:
|
|
'VOID is a minimalist, typography-oriented theme that brings elegance to your reading experience.',
|
|
date: 'Jul 11, 2026',
|
|
slug: 'beauty-of-void',
|
|
cover: null
|
|
}
|
|
]
|
|
};
|
|
}
|
|
|
|
try {
|
|
// Optimization: Use substr to prevent fetching megabytes of content just for excerpts
|
|
const { results } = await db
|
|
.prepare(
|
|
`SELECT p.id, p.slug, p.title, SUBSTR(p.content, 1, 2000) AS content, p.cover, p.published_at as date
|
|
FROM posts p
|
|
ORDER BY p.published_at DESC LIMIT 10`
|
|
)
|
|
.all();
|
|
|
|
// Convert date to string for serialization
|
|
const formattedPosts = results.map((post) => {
|
|
const d = new Date(post.date as string);
|
|
const month = d.toLocaleString('en-US', { month: 'short' });
|
|
const day = d.getDate();
|
|
const year = d.getFullYear();
|
|
|
|
// Prefer the manually marked summary, otherwise derive it from the beginning
|
|
const contentStr = ((post.content as string) || '').split('<!--more-->')[0];
|
|
|
|
// The excerpt is plain text: no Markdown markers and no trailing ellipsis
|
|
const excerpt = createExcerpt(contentStr);
|
|
|
|
// Do not send full content to the list view to save bandwidth
|
|
|
|
return {
|
|
id: post.id as number,
|
|
title: post.title as string,
|
|
slug: post.slug as string,
|
|
cover: post.cover as string | null,
|
|
date: `${month} ${day}, ${year}`,
|
|
excerpt
|
|
};
|
|
});
|
|
|
|
return {
|
|
posts: formattedPosts
|
|
};
|
|
} catch (err: any) {
|
|
console.error('Error fetching posts from D1:', err);
|
|
return { posts: [] };
|
|
}
|
|
};
|