93 lines
2.0 KiB
TypeScript
93 lines
2.0 KiB
TypeScript
"use server";
|
|
|
|
import { s3 } from "@/lib/s3";
|
|
import {
|
|
DeleteObjectCommand,
|
|
ListObjectsV2Command,
|
|
PutObjectCommand,
|
|
} from "@aws-sdk/client-s3";
|
|
|
|
const PREFIX = "commissions/examples/";
|
|
|
|
export type CommissionExampleItem = {
|
|
key: string;
|
|
url: string;
|
|
size: number | null;
|
|
lastModified: string | null;
|
|
};
|
|
|
|
function buildImageUrl(key: string) {
|
|
return `/api/image/${encodeURI(key)}`;
|
|
}
|
|
|
|
function sanitizeFilename(name: string) {
|
|
return name.replace(/[^a-zA-Z0-9._-]/g, "_");
|
|
}
|
|
|
|
export async function listCommissionExamples(): Promise<CommissionExampleItem[]> {
|
|
const command = new ListObjectsV2Command({
|
|
Bucket: `${process.env.BUCKET_NAME}`,
|
|
Prefix: PREFIX,
|
|
});
|
|
|
|
const res = await s3.send(command);
|
|
return (
|
|
res.Contents?.filter((obj) => obj.Key && obj.Key !== PREFIX).map((obj) => {
|
|
const key = obj.Key as string;
|
|
return {
|
|
key,
|
|
url: buildImageUrl(key),
|
|
size: obj.Size ?? null,
|
|
lastModified: obj.LastModified?.toISOString() ?? null,
|
|
};
|
|
}) ?? []
|
|
);
|
|
}
|
|
|
|
export async function uploadCommissionExample(
|
|
formData: FormData
|
|
): Promise<CommissionExampleItem> {
|
|
const file = formData.get("file");
|
|
|
|
if (!(file instanceof File)) {
|
|
throw new Error("Missing file");
|
|
}
|
|
|
|
if (!file.type.startsWith("image/")) {
|
|
throw new Error("Only image uploads are allowed");
|
|
}
|
|
|
|
const safeName = sanitizeFilename(file.name || "example");
|
|
const key = `${PREFIX}${Date.now()}-${safeName}`;
|
|
const buffer = Buffer.from(await file.arrayBuffer());
|
|
|
|
await s3.send(
|
|
new PutObjectCommand({
|
|
Bucket: `${process.env.BUCKET_NAME}`,
|
|
Key: key,
|
|
Body: buffer,
|
|
ContentType: file.type,
|
|
})
|
|
);
|
|
|
|
return {
|
|
key,
|
|
url: buildImageUrl(key),
|
|
size: file.size,
|
|
lastModified: new Date().toISOString(),
|
|
};
|
|
}
|
|
|
|
export async function deleteCommissionExample(key: string) {
|
|
if (!key.startsWith(PREFIX)) {
|
|
throw new Error("Invalid key");
|
|
}
|
|
|
|
await s3.send(
|
|
new DeleteObjectCommand({
|
|
Bucket: `${process.env.BUCKET_NAME}`,
|
|
Key: key,
|
|
})
|
|
);
|
|
}
|