Files
azure-image-chooser/app/frontend/src/api.ts

56 lines
2.3 KiB
TypeScript

import type { LocationOption, SelectionState, UsageTemplate } from "./types";
const json = async <T>(path: string): Promise<T> => {
const response = await fetch(path);
if (!response.ok) {
let details = "";
try {
const payload = (await response.json()) as { message?: string };
details = payload.message ?? "";
} catch {
// Ignore non-JSON error payloads.
}
throw new Error(details || `Request failed for ${path} (${response.status})`);
}
return (await response.json()) as T;
};
export const api = {
health: () => json<{ status: string; message?: string }>("/api/health"),
locations: () => json<LocationOption[]>("/api/locations"),
publishers: (location: string) => json<string[]>(`/api/publishers?location=${encodeURIComponent(location)}`),
offers: (location: string, publisher: string) =>
json<string[]>(`/api/offers?location=${encodeURIComponent(location)}&publisher=${encodeURIComponent(publisher)}`),
skus: (location: string, publisher: string, offer: string) =>
json<string[]>(
`/api/skus?location=${encodeURIComponent(location)}&publisher=${encodeURIComponent(publisher)}&offer=${encodeURIComponent(offer)}`
),
versions: (location: string, publisher: string, offer: string, sku: string) =>
json<string[]>(
`/api/versions?location=${encodeURIComponent(location)}&publisher=${encodeURIComponent(publisher)}&offer=${encodeURIComponent(offer)}&sku=${encodeURIComponent(sku)}`
),
templates: () => json<UsageTemplate[]>("/api/templates"),
render: async (templateFile: string, selection: SelectionState): Promise<string> => {
const response = await fetch("/api/render", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ templateFile, selection })
});
if (!response.ok) {
throw new Error("Failed to render template");
}
const payload = (await response.json()) as { rendered: string };
return payload.rendered;
},
skuExport: async (location: string, publisher: string, offer: string): Promise<string> => {
const payload = await json<{ rendered: string }>(
`/api/sku-export?location=${encodeURIComponent(location)}&publisher=${encodeURIComponent(publisher)}&offer=${encodeURIComponent(offer)}`
);
return payload.rendered;
}
};