91 lines
2.1 KiB
TypeScript
91 lines
2.1 KiB
TypeScript
import { db } from '$lib/server/db';
|
|
import { blogArticles } from '$lib/server/db/schema';
|
|
import { isAdmin, requireAdmin } from '$lib/server/auth';
|
|
import { updateArticleSchema } from '$lib/validation/blog';
|
|
import { eq } from 'drizzle-orm';
|
|
import { error, fail, redirect } from '@sveltejs/kit';
|
|
|
|
import type { PageServerLoad } from './$types.js';
|
|
|
|
export const load: PageServerLoad = async (event) => {
|
|
if (!isAdmin(event)) {
|
|
return redirect(303, `/blog/${event.params.slug}`);
|
|
}
|
|
|
|
const [article] = await db
|
|
.select()
|
|
.from(blogArticles)
|
|
.where(eq(blogArticles.slug, event.params.slug));
|
|
|
|
if (!article) {
|
|
return error(404, { message: 'Article not found' });
|
|
}
|
|
|
|
return {
|
|
blogArticle: article
|
|
};
|
|
};
|
|
|
|
export const actions = {
|
|
save: async (event) => {
|
|
requireAdmin(event);
|
|
|
|
const formData = await event.request.formData();
|
|
const parsed = updateArticleSchema.safeParse({
|
|
title: formData.get('title')?.toString(),
|
|
content: formData.get('content')?.toString()
|
|
});
|
|
|
|
if (!parsed.success) {
|
|
return fail(400, { message: 'Title and content are required' });
|
|
}
|
|
|
|
const [updated] = await db
|
|
.update(blogArticles)
|
|
.set({
|
|
title: parsed.data.title,
|
|
content: parsed.data.content,
|
|
updatedAt: new Date()
|
|
})
|
|
.where(eq(blogArticles.slug, event.params.slug))
|
|
.returning();
|
|
|
|
if (!updated) {
|
|
return error(404, { message: 'Article not found' });
|
|
}
|
|
|
|
return { saved: true };
|
|
},
|
|
|
|
publish: async (event) => {
|
|
requireAdmin(event);
|
|
|
|
const formData = await event.request.formData();
|
|
const parsed = updateArticleSchema.safeParse({
|
|
title: formData.get('title')?.toString(),
|
|
content: formData.get('content')?.toString()
|
|
});
|
|
|
|
if (!parsed.success) {
|
|
return fail(400, { message: 'Title and content are required' });
|
|
}
|
|
|
|
const [updated] = await db
|
|
.update(blogArticles)
|
|
.set({
|
|
title: parsed.data.title,
|
|
content: parsed.data.content,
|
|
status: 'published',
|
|
updatedAt: new Date()
|
|
})
|
|
.where(eq(blogArticles.slug, event.params.slug))
|
|
.returning();
|
|
|
|
if (!updated) {
|
|
return error(404, { message: 'Article not found' });
|
|
}
|
|
|
|
return redirect(303, `/blog/${updated.slug}`);
|
|
}
|
|
};
|