import {z} from 'zod' export type GetApiApikeyWeatherLatLonArgs = {apikey: string, lat: number, lon: number, 'X-Delimiter'?: string | undefined, 'X-Separator'?: string | undefined}; export type GetApiApikeyWeatherLatLonOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const datasetWeather = z.object({datetime: z.string().optional(), timestamp: z.number().optional(), sky: z.number().gte(0).lte(1).optional(), temperature: z.number().optional(), condition: z.string().optional(), icon: z.string().optional(), wind_speed: z.number().optional(), wind_degrees: z.number().gte(0).lte(360).optional(), wind_direction: z.number().optional()}); export const messageOk = z.object({code: z.number().int().optional(), type: z.string().optional(), text: z.string().optional()}); export const responseWeather = z.object({result: z.array(datasetWeather).optional(), message: messageOk.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 }; /** * Get weather forecast for a location * * GET /{apikey}/weather/{lat}/{lon} */ export const getApiApikeyWeatherLatLon = async (args: GetApiApikeyWeatherLatLonArgs, options: GetApiApikeyWeatherLatLonOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args['X-Delimiter'] != null) headers.set("X-Delimiter", String(args['X-Delimiter'])) if (args['X-Separator'] != null) headers.set("X-Separator", String(args['X-Separator'])) const url = `${baseUrl.replace(/\/+$/, '')}/${encodeURIComponent(String(args.apikey))}/weather/${encodeURIComponent(String(args.lat))}/${encodeURIComponent(String(args.lon))}${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(responseWeather, await res.json()) };