pse2_ff/project/frontend/src/util/api.ts

122 lines
2.3 KiB
TypeScript

import type { Kennzahl } from "@/types/kpi";
const API_HOST = import.meta.env.VITE_API_HOST || 'http://localhost:5050';
export { API_HOST };
export const fetchKPI = async (
pitchBookId: string,
): Promise<{
[key: string]: {
label: string;
entity: string;
page: number;
status: string;
source: string;
}[];
}> => {
const response = await fetch(
`${API_HOST}/api/pitch_book/${pitchBookId}`,
);
const data = await response.json();
return data.kpi ? getKPI(data.kpi) : {};
};
export const fetchPutKPI = async (
pitchBookId: number,
kpi: {
[key: string]: {
label: string;
entity: string;
page: number;
status: string;
source: string;
}[];
},
): Promise<{
[key: string]: {
label: string;
entity: string;
page: number;
status: string;
source: string;
}[];
}> => {
const formData = new FormData();
formData.append("kpi", JSON.stringify(flattenKPIArray(kpi)));
const response = await fetch(
`${API_HOST}/api/pitch_book/${pitchBookId}`,
{
method: "PUT",
body: formData,
},
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return getKPI(data.kpi);
};
const getKPI = (data: string) => {
const kpi = JSON.parse(data) as {
label: string;
entity: string;
page: number;
status: string;
source: string;
}[];
const reducedKpi = kpi.reduce(
(prev, curr) => {
if (!prev[curr.label]) {
prev[curr.label] = [];
}
prev[curr.label].push(curr);
return prev;
},
{} as {
[key: string]: {
label: string;
entity: string;
page: number;
status: string;
source: string;
}[];
},
);
return reducedKpi;
};
export const flattenKPIArray = (kpi: {
[key: string]: {
label: string;
entity: string;
page: number;
status: string;
source: string;
}[];
}) => {
return Object.values(kpi).flat();
};
export const fetchKennzahlen = async (): Promise<Kennzahl[]> => {
const response = await fetch(`${API_HOST}/api/kpi_setting/`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data;
};
export async function fetchPitchBooks() {
const response = await fetch(`${API_HOST}/api/pitch_book/`);
if (!response.ok) {
throw new Error("Failed to fetch pitch books");
}
return response.json();
}