Files
online-energieausweis/src/client/lib/bilderHochladen.ts
Moritz Utcke d228908430 Fehler Behoben
2025-02-20 10:11:09 +11:00

96 lines
2.7 KiB
TypeScript

import {
ObjektClient,
UploadedGebaeudeBild,
VerbrauchsausweisWohnenClient,
} from "#components/Ausweis/types.js";
import { API_ACCESS_TOKEN_COOKIE_NAME } from "#lib/constants.js";
import { Enums } from "@ibcornelsen/database/client";
import { addNotification, updateNotification } from "@ibcornelsen/ui";
import { api } from "astro-typesafe-api/client";
import Cookies from "js-cookie";
export async function bilderHochladen(
images: (UploadedGebaeudeBild & { base64?: string, update?: boolean })[],
aufnahme_uid: string
) {
if (images.length == 0) {
return images;
}
// Wenn Bilder hochgeladen werden konvertieren wir sie zu base64, das heißt, dass die base64 Eigenschaft bei diesen Bildern
// existiert. Das müssen wir TypeScript nur wissen lassen, damit es uns in Ruhe lässt.
const imagesToUpload = images.filter(
(image) => !image.uid || image.update
) as unknown as {
data: string;
kategorie: string;
uid?: string;
update: boolean;
}[];
if (imagesToUpload.length == 0) {
return images;
}
// Alle Bilder hochladen
const notification = addNotification({
dismissable: false,
message: "Bilder hochladen.",
subtext: `${imagesToUpload.length} Bilder werden hochgeladen, bitte haben sie Geduld.`,
timeout: 0,
type: "info",
});
for (let i = 0; i < imagesToUpload.length; i++) {
const image = imagesToUpload[i];
try {
if (image.update) {
await api.bilder._uid.PATCH.fetch({
data: image.data,
kategorie: image.kategorie as Enums.BilderKategorie,
}, {
params: {
uid: image.uid as string,
},
headers: {
"Authorization": `Bearer ${Cookies.get(API_ACCESS_TOKEN_COOKIE_NAME)}`
}
});
} else {
const response = await api.aufnahme._uid.bilder.PUT.fetch({
data: image.data,
kategorie: image.kategorie as Enums.BilderKategorie
}, {
params: {
uid: aufnahme_uid
},
headers: {
"Authorization": `Bearer ${Cookies.get(API_ACCESS_TOKEN_COOKIE_NAME)}`
}
});
image.uid = response.uid;
}
updateNotification(notification, {
dismissable: true,
message: "Bild hochgeladen.",
subtext: `${i + 1}/${
imagesToUpload.length
} Bildern wurden erfolgreich hochgeladen.`,
timeout: 3000,
});
} catch (e) {
updateNotification(notification, {
dismissable: true,
message: "Bild konnte nicht hochgeladen werden.",
subtext: `Eines ihrer Bilder konnte nicht hochgeladen werden. Wir haben bereits ein Ticket erstellt und melden uns so schnell wie möglich bei ihnen.`,
timeout: 15000,
type: "error",
});
}
}
return images;
}