add blog editor
This commit is contained in:
90
src/routes/blog/[slug]/edit/+page.server.ts
Normal file
90
src/routes/blog/[slug]/edit/+page.server.ts
Normal file
@@ -0,0 +1,90 @@
|
||||
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}`);
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user