infoalloggi-monorepo/apps/infoalloggi/src/lib/storage_manager.ts

97 lines
2 KiB
TypeScript
Raw Normal View History

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