import {z} from 'zod' export type GetApiInstalledPowerArgs = {country?: string | undefined, time_step?: string | undefined, installation_decommission?: boolean | undefined}; export type GetApiInstalledPowerOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const namedData = z.object({name: z.string(), data: z.array(z.number().nullable())}); export const installedModel = z.object({time: z.array(z.string()), production_types: z.array(namedData).nullable().optional(), last_update: z.number().int().nullable(), deprecated: z.boolean()}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Installed Power * * GET /installed_power */ export const getApiInstalledPower = async (args: GetApiInstalledPowerArgs, options: GetApiInstalledPowerOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.country != null) query.append("country", String(args.country)) if (args.time_step != null) query.append("time_step", String(args.time_step)) if (args.installation_decommission != null) query.append("installation_decommission", String(args.installation_decommission)) const url = `${baseUrl.replace(/\/+$/, '')}/installed_power${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(installedModel, await res.json()) };