import {z} from 'zod' export type GetApiWeatherArgs = {key: string, iataCode: string}; export type GetApiWeatherOptions = {baseUrl?: string | undefined, key?: string | undefined, fetch?: typeof fetch | undefined}; export const getApiWeatherResponse = z.object({airportIcao: z.string().optional(), airportIata: z.string().optional(), airportName: z.string().optional(), latitude: z.number().optional(), longitude: z.number().optional(), currentWeather: z.object({temp: z.number().optional(), humidity: z.number().int().optional(), pressureMm: z.number().optional(), windMps: z.number().optional(), windDir: z.number().int().optional(), condition: z.string().optional(), precipitation: z.number().optional()}).optional(), forecast: z.array(z.object({timeFrom: z.string().optional(), timeTo: z.string().optional(), temp: z.number().optional(), humidity: z.number().int().optional(), pressureMm: z.number().optional(), windMps: z.number().optional(), windDir: z.number().int().optional(), condition: z.string().optional(), precipitation: z.number().optional()})).optional()}); 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 }; /** * Retrieve current weather conditions and forecasts for an airport using its IATA code. * * GET /weather */ export const getApiWeather = async (args: GetApiWeatherArgs, options?: GetApiWeatherOptions) => { const {baseUrl = "https://aviation-edge.com/v2/public", fetch: fetchFn = fetch, key} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.key != null) query.append("key", String(args.key)) if (args.iataCode != null) query.append("iataCode", String(args.iataCode)) if (key !== undefined) query.set("key", key) const url = `${baseUrl.replace(/\/+$/, '')}/weather${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(getApiWeatherResponse, await res.json()) };