import {z} from 'zod' export type GetApiStationsSearchArgs = {apikey: string, lat: number, lng: number, rad?: number | undefined}; export type GetApiStationsSearchOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const station = z.object({country: z.string().optional(), id: z.string(), name: z.string().optional(), brand: z.string().optional(), street: z.string().optional(), postalCode: z.string(), place: z.string().optional(), coords: z.object({lat: z.number(), lng: z.number()}), isOpen: z.boolean().optional(), closesAt: z.string().optional(), opensAt: z.string().optional(), openingTimes: z.array(z.object({days: z.array(z.enum(["mon", "tue", "wed", "thu", "fri", "sat", "sun", "hol"])).optional(), times: z.array(z.object({open: z.string().optional(), close: z.string().optional()})).optional()})).optional(), dist: z.number().optional(), fuels: z.array(z.object({category: z.enum(["diesel", "lpg", "gasoline", "cng"]), name: z.string(), price: z.number(), lastChange: z.object({timestamp: z.string(), amount: z.number()}).optional()}))}); export const stations = z.array(station); export const response200 = z.object({apiVersion: z.string(), timestamp: z.string(), stations: stations}); 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 }; /** * Aktuelle Kraftstoffpreise an Tankstellen im Umkreis * * GET /stations/search */ export const getApiStationsSearch = async (args: GetApiStationsSearchArgs, options?: GetApiStationsSearchOptions) => { const {baseUrl = "https://creativecommons.tankerkoenig.de/api/v4", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json; charset=utf-8") if (args.apikey != null) query.append("apikey", String(args.apikey)) if (args.lat != null) query.append("lat", String(args.lat)) if (args.lng != null) query.append("lng", String(args.lng)) if (args.rad != null) query.append("rad", String(args.rad)) const url = `${baseUrl.replace(/\/+$/, '')}/stations/search${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(response200, await res.json()) };