infoalloggi-monorepo/apps/infoalloggi/src/lib/storage_manager.ts
2025-08-29 16:18:32 +02:00

96 lines
2 KiB
TypeScript

import type { TempTokensToken } from "~/schemas/public/TempTokens";
export const Upload = async ({
files,
getToken,
from_admin,
}: {
files: File[];
getToken: ({ num }: { num: number }) => Promise<TempTokensToken[]>;
from_admin: boolean;
}) => {
const attachments = [];
if (files.length === 0) {
console.error("No files provided");
return { attachments: [], error: "No files provided", status: false };
}
if (files.length > 1) {
const authTokens = await getToken({
num: files.length,
});
if (authTokens.length !== files.length) {
console.error(
"Error: number of tokens does not match number of files",
authTokens.length,
files.length,
);
return {
attachments: [],
error: "Error: number of tokens does not match number of files",
status: false,
};
}
for (const file of files) {
const attach = await uploadFile({
file,
from_admin,
// biome-ignore lint/style/noNonNullAssertion: <intended>
token: authTokens.pop()!,
});
attachments.push(attach);
}
} else {
const authTokens = (
await getToken({
num: 1,
})
)[0];
if (!authTokens) {
console.error("Error: no token received");
return {
attachments: [],
error: "Error: no token received",
status: false,
};
}
const attach = await uploadFile({
// biome-ignore lint/style/noNonNullAssertion: <intended>
file: files[0]!,
from_admin,
token: authTokens,
});
attachments.push(attach);
}
return { attachments, status: true };
};
const uploadFile = async ({
file,
token,
from_admin,
}: {
file: File;
token: TempTokensToken;
from_admin: boolean;
}) => {
const formData = new FormData();
formData.append("file", file);
const response = await fetch(
`/go-api/storage/upload?token=${token}&from_admin=${from_admin}`,
{
body: formData,
method: "POST",
},
);
if (!response.ok) {
throw new Error(
`Error uploading file: ${response.status} ${response.statusText}`,
);
}
return response.text();
};