Add media helper for R2 keys and cleanup
This commit is contained in:
@@ -0,0 +1,28 @@
|
||||
import type { AppEnv } from "./env";
|
||||
|
||||
export const MEDIA_PREFIX = "/media/";
|
||||
|
||||
/** 由 R2 key 砌出對外 URL。 */
|
||||
export function mediaUrl(key: string): string {
|
||||
return `${MEDIA_PREFIX}${key}`;
|
||||
}
|
||||
|
||||
/** 由 /media/... URL 取出 R2 key;唔係 /media/ 開頭回 null。 */
|
||||
export function mediaKey(url: string | null | undefined): string | null {
|
||||
if (!url || !url.startsWith(MEDIA_PREFIX)) return null;
|
||||
return url.slice(MEDIA_PREFIX.length);
|
||||
}
|
||||
|
||||
/** 刪除 /media/... 對應嘅 R2 物件;外部 URL 或空值唔理,唔會 throw。 */
|
||||
export async function deleteMedia(
|
||||
env: AppEnv,
|
||||
url: string | null | undefined,
|
||||
): Promise<void> {
|
||||
const key = mediaKey(url);
|
||||
if (!key) return;
|
||||
try {
|
||||
await env.MEDIA.delete(key);
|
||||
} catch {
|
||||
// 刪除失敗唔應該阻礙儲存流程。
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user