67 lines
1.6 KiB
TypeScript
67 lines
1.6 KiB
TypeScript
import { mkdir, rm, writeFile } from "node:fs/promises"
|
|
import path from "node:path"
|
|
|
|
import { buildMediaStorageKey } from "@/lib/media/storage-key"
|
|
|
|
type StoreLocalUploadParams = {
|
|
file: File
|
|
tenantId: string
|
|
assetId: string
|
|
fileRole: string
|
|
variant: string
|
|
}
|
|
|
|
type StoredUpload = {
|
|
storageKey: string
|
|
}
|
|
|
|
export function resolveLocalMediaBaseDirectory(): string {
|
|
const configured = process.env.CMS_MEDIA_LOCAL_STORAGE_DIR?.trim()
|
|
|
|
if (configured) {
|
|
return path.resolve(configured)
|
|
}
|
|
|
|
return path.resolve(process.cwd(), ".data", "media")
|
|
}
|
|
|
|
export async function storeUploadLocally(params: StoreLocalUploadParams): Promise<StoredUpload> {
|
|
const storageKey = buildMediaStorageKey({
|
|
tenantId: params.tenantId,
|
|
assetId: params.assetId,
|
|
fileRole: params.fileRole,
|
|
variant: params.variant,
|
|
fileName: params.file.name,
|
|
})
|
|
const baseDirectory = resolveLocalMediaBaseDirectory()
|
|
const outputPath = path.join(baseDirectory, storageKey)
|
|
|
|
await mkdir(path.dirname(outputPath), { recursive: true })
|
|
|
|
const bytes = new Uint8Array(await params.file.arrayBuffer())
|
|
await writeFile(outputPath, bytes)
|
|
|
|
return { storageKey }
|
|
}
|
|
|
|
export async function deleteLocalStorageObject(storageKey: string): Promise<boolean> {
|
|
const baseDirectory = resolveLocalMediaBaseDirectory()
|
|
const outputPath = path.join(baseDirectory, storageKey)
|
|
|
|
try {
|
|
await rm(outputPath)
|
|
return true
|
|
} catch (error) {
|
|
const code =
|
|
typeof error === "object" && error !== null && "code" in error
|
|
? String((error as { code?: unknown }).code)
|
|
: ""
|
|
|
|
if (code === "ENOENT") {
|
|
return false
|
|
}
|
|
|
|
throw error
|
|
}
|
|
}
|