import {z} from 'zod' export type GetApiTxcxnArgs = {west: unknown, south: unknown, east: unknown, north: unknown, skip: unknown, take: unknown}; export type GetApiTxcxnOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const telexConnection = z.object({id: z.string(), isActive: z.boolean(), firstContact: z.string(), lastContact: z.string(), flight: z.string(), location: z.object({x: z.number(), y: z.number()}), trueAltitude: z.number(), heading: z.number().gte(0).lte(360), freetextEnabled: z.boolean(), aircraftType: z.string(), origin: z.string().optional(), destination: z.string().optional()}); export const paginatedTelexConnectionDto = z.object({results: z.array(telexConnection), count: 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 /txcxn */ export const getApiTxcxn = async (args: GetApiTxcxnArgs, options: GetApiTxcxnOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.west != null) query.append("west", String(args.west)) if (args.south != null) query.append("south", String(args.south)) if (args.east != null) query.append("east", String(args.east)) if (args.north != null) query.append("north", String(args.north)) if (args.skip != null) query.append("skip", String(args.skip)) if (args.take != null) query.append("take", String(args.take)) const url = `${baseUrl.replace(/\/+$/, '')}/txcxn${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(paginatedTelexConnectionDto, await res.json()) };