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