70 lines
1.9 KiB
TypeScript
70 lines
1.9 KiB
TypeScript
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
|
|
import { error, fail, redirect } from '@sveltejs/kit';
|
|
import type { Actions, PageServerLoad } from './$types';
|
|
|
|
export const load: PageServerLoad = async ({ params, platform }) => {
|
|
const db = platform?.env?.DB;
|
|
const pageId = params.id;
|
|
|
|
if (!db) {
|
|
throw error(500, '数据库未连接');
|
|
}
|
|
|
|
try {
|
|
const page = await db
|
|
.prepare('SELECT id, title, slug, content FROM pages WHERE id = ?')
|
|
.bind(pageId)
|
|
.first<{ id: number; title: string; slug: string; content: string }>();
|
|
|
|
if (!page) {
|
|
throw error(404, '页面不存在');
|
|
}
|
|
|
|
return {
|
|
page
|
|
};
|
|
} catch (err: unknown) {
|
|
if ((err as any)?.status === 404) throw err;
|
|
console.error('Error loading page for edit:', err);
|
|
throw error(500, '读取页面详情失败');
|
|
}
|
|
};
|
|
|
|
export const actions: Actions = {
|
|
update: async ({ params, request, platform }) => {
|
|
const db = platform?.env?.DB;
|
|
const pageId = params.id;
|
|
|
|
if (!db) return fail(500, { error: '数据库未连接' });
|
|
|
|
const formData = await request.formData();
|
|
const title = formData.get('title')?.toString().trim();
|
|
const slug = formData.get('slug')?.toString().trim();
|
|
const content = formData.get('content')?.toString() || '';
|
|
|
|
if (!title || !slug || !content) {
|
|
return fail(400, { error: '标题、URL 别名和正文为必填项' });
|
|
}
|
|
|
|
try {
|
|
await db
|
|
.prepare(
|
|
`UPDATE pages
|
|
SET title = ?, slug = ?, content = ?, updated_at = CURRENT_TIMESTAMP
|
|
WHERE id = ?`
|
|
)
|
|
.bind(title, slug, content, pageId)
|
|
.run();
|
|
} catch (err: unknown) {
|
|
console.error('Error updating page:', err);
|
|
if ((err as any)?.message?.includes('UNIQUE constraint failed')) {
|
|
return fail(400, { error: 'URL 别名已被其他页面占用' });
|
|
}
|
|
return fail(500, { error: '保存修改失败' });
|
|
}
|
|
|
|
throw redirect(303, '/admin/pages');
|
|
}
|
|
};
|