import {z} from 'zod' export type YearMonth = string; export type GetApiV1ProductsArgs = {yearMonth: YearMonth, energyType?: ('ELECTRICITY' | 'GAS') | undefined, contractType?: ('CONSUMPTION' | 'INJECTION') | undefined, priceModel?: ('FIXED' | 'VARIABLE' | 'DYNAMIC') | undefined, search?: string | undefined, offset?: number | undefined, limit?: number | undefined}; export type GetApiV1ProductsOptions = {baseUrl?: string | undefined, apiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const country = z.string().min(2).max(2); export const merchant = z.object({id: z.string(), canonicalName: z.string(), displayName: z.string(), website: z.string().nullable(), hasNativeApp: z.boolean().nullable(), cooperative: z.boolean().nullable(), automatedSwitch: z.boolean(), vregServicecheckRating: z.number().int().gte(1).lte(5).nullable(), vregComplaintsPerThousand: z.number().gte(0).nullable(), country: country}); export const productWithUsps = z.object({id: z.string(), productName: z.string(), energyType: z.enum(["ELECTRICITY", "GAS"]), priceModel: z.enum(["FIXED", "VARIABLE", "DYNAMIC"]), subType: z.string().nullable(), serviceArea: z.object({country: country, region: z.enum(["Flanders", "BrusselsCapitalRegion", "Wallonia"])}), characteristics: z.object({directDebitOnly: z.boolean().nullable(), emailInvoiceOnly: z.boolean().nullable(), onlineServiceOnly: z.boolean().nullable(), greenEnergy: z.boolean().nullable(), greenEnergyAndLocal: z.boolean().nullable(), contractDuration: z.enum(["1 year", "2 years", "3 years", "4 years", "5 years", "10 years", "UNDETERMINED"]).nullable(), priceCertaintyPeriod: z.enum(["none", "1 month", "2 months", "3 months", "4 months", "5 months", "6 months", "7 months", "8 months", "9 months", "10 months", "11 months", "1 year", "2 years", "3 years", "4 years", "5 years", "10 years"]).nullable(), onlyForClientWithSolar: z.boolean().nullable(), onlyForClientWithEV: z.boolean().nullable(), includesSolarPanels: z.boolean().nullable(), includesChargingStation: z.boolean().nullable(), groupPurchase: z.boolean().nullable(), cooperative: z.boolean().nullable()}), conditions: z.array(z.object({title: z.string(), description: z.string().nullable()})), merchant: merchant, usps: z.array(z.object({label: z.string(), description: z.string().nullable()}))}); export const getApiV1ProductsResponse = z.object({data: z.array(productWithUsps), meta: z.object({offset: z.number(), limit: z.number(), total: z.number()})}); 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 }; /** * Get all energy products * * GET /v1/products */ export const getApiV1Products = async (args: GetApiV1ProductsArgs, options?: GetApiV1ProductsOptions) => { const {baseUrl = "https://open-energie.api.vwala.be", fetch: fetchFn = fetch, apiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.yearMonth != null) query.append("yearMonth", String(args.yearMonth)) if (args.energyType != null) query.append("energyType", String(args.energyType)) if (args.contractType != null) query.append("contractType", String(args.contractType)) if (args.priceModel != null) query.append("priceModel", String(args.priceModel)) if (args.search != null) query.append("search", String(args.search)) if (args.offset != null) query.append("offset", String(args.offset)) if (args.limit != null) query.append("limit", String(args.limit)) if (apiKey !== undefined) headers.set("x-api-key", apiKey) const url = `${baseUrl.replace(/\/+$/, '')}/v1/products${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(getApiV1ProductsResponse, await res.json()) };