Add cover image upload to blog posts with cleanup
This commit is contained in:
@@ -8,12 +8,15 @@ import { getEnv } from "../../../lib/env";
|
||||
import { uniqueSlug } from "../../../data/content";
|
||||
import { parseForm } from "../../../lib/form";
|
||||
import { postInput } from "../../../schemas";
|
||||
import ImageField from "../../../components/admin/ImageField.astro";
|
||||
import { deleteMedia } from "../../../lib/media";
|
||||
|
||||
export const prerender = false;
|
||||
|
||||
const { id } = Astro.params;
|
||||
const isNew = id === "new";
|
||||
const db = getDb(getEnv().DB);
|
||||
const env = getEnv();
|
||||
const db = getDb(env.DB);
|
||||
|
||||
let error = "";
|
||||
let errors: Record<string, string> = {};
|
||||
@@ -31,6 +34,7 @@ if (Astro.request.method === "POST") {
|
||||
const action = String(form.get("action") ?? "save");
|
||||
|
||||
if (action === "delete" && !isNew) {
|
||||
await deleteMedia(env, existing?.coverImage);
|
||||
await db.delete(posts).where(eq(posts.id, id!));
|
||||
return Astro.redirect("/admin");
|
||||
}
|
||||
@@ -69,6 +73,9 @@ if (Astro.request.method === "POST") {
|
||||
updatedAt: now,
|
||||
});
|
||||
} else {
|
||||
if (existing!.coverImage !== coverImage) {
|
||||
await deleteMedia(env, existing!.coverImage);
|
||||
}
|
||||
await db
|
||||
.update(posts)
|
||||
.set({
|
||||
@@ -129,14 +136,13 @@ const post = isNew
|
||||
placeholder="留空會由內容自動產生"
|
||||
/>
|
||||
|
||||
<label for="coverImage">封面圖片 URL(列表卡片用)</label>
|
||||
{errors.coverImage && <span class="field-error">{errors.coverImage}</span>}
|
||||
<input
|
||||
id="coverImage"
|
||||
<ImageField
|
||||
name="coverImage"
|
||||
type="text"
|
||||
value={post.coverImage ?? ""}
|
||||
placeholder="https://..."
|
||||
label="封面圖片(列表卡片用)"
|
||||
scope="posts"
|
||||
value={post.coverImage}
|
||||
id="coverImage"
|
||||
/>
|
||||
|
||||
<label for="tags">標籤(逗號分隔,可選)</label>
|
||||
|
||||
Reference in New Issue
Block a user