infoalloggi-monorepo/apps/infoalloggi/src/hooks/storageClienSideHooks.ts

84 lines
1.7 KiB
TypeScript
Raw Normal View History

2025-10-24 16:10:59 +02:00
import { add } from "date-fns";
import z from "zod";
type UploadResponse =
| {
success: true;
id: string;
}
| {
success: false;
error: string;
};
// Helper to handle file uploads
export async function uploadFile(
file: File,
expiresAt: string | undefined,
): Promise<UploadResponse> {
const formData = new FormData();
formData.append("file", file);
if (expiresAt) {
formData.append("expires_at", expiresAt);
}
try {
const response = await fetch(`/storage-api/upload`, {
method: "POST",
body: formData,
});
if (response.ok) {
const res = await response.json();
const parsed = z
.object({
id: z.string(),
})
.parse(res);
const fileID = parsed.id;
console.log("File uploaded successfully.");
return { success: true, id: fileID };
}
return {
success: false,
error: `Caricamento fallito con status: ${response.status}`,
};
} catch (e) {
return {
success: false,
error: `Errore caricamento file: ${(e as Error).message}`,
};
}
}
export const uploadHandler = async ({
files,
from_admin,
}: {
files: File[];
from_admin: boolean;
}) => {
const attachments = [];
const failed: string[] = [];
const expirationDate = add(new Date(), { days: 60 }).toISOString();
if (files.length === 0) {
console.error("No files provided");
return { attachments: [], error: "No files provided", status: false };
}
for (const file of files) {
const upload = await uploadFile(
file,
from_admin ? expirationDate : undefined,
);
if (upload.success) {
attachments.push(upload.id);
} else {
console.error(`Error uploading file ${file.name}: ${upload.error}`);
failed.push(file.name);
}
}
return { attachments, failed, status: true };
};