Files
blogflare/src/routes/+page.server.ts
T

80 lines
2.2 KiB
TypeScript

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'
},
{
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'
}
]
};
}
try {
const { results } = await db.prepare(
`SELECT p.id, p.slug, p.title, p.content, 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();
let excerpt = '';
let contentStr = post.content as string || '';
// Filter out Hugo shortcodes like {{< admonition abstract "标题" >}}
contentStr = contentStr.replace(/\{\{<[\s\S]*?>\}\}/g, '');
const parts = contentStr.split('<!--more-->');
if (parts.length > 1) {
excerpt = parts[0].trim();
} else {
// Strip basic markdown syntax for the automatic excerpt
let plainText = contentStr.replace(/[#*\`>~\\[\\]\\(\\)\\-]/g, '').trim();
excerpt = plainText.substring(0, 150).trim();
}
// Append ... to indicate there is more to read
if (excerpt && !excerpt.endsWith('...')) {
excerpt += '...';
}
// Do not send full content to the list view to save bandwidth
const { content, ...restPost } = post as any;
return {
...restPost,
date: `${month} ${day}, ${year}`,
excerpt
};
});
return {
posts: formattedPosts
};
} catch (err) {
console.error('Error fetching posts from D1:', err);
return { posts: [] };
}
};