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

90 lines
2.3 KiB
TypeScript

/* eslint-disable @typescript-eslint/no-explicit-any */
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 {
const { results } = await db
.prepare(
`SELECT p.id, p.slug, p.title, p.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();
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
const 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
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: [] };
}
};