import {z} from 'zod' export type BaseLevel = 'planet' | 'continent' | 'country' | 'region' | 'county' | 'localadmin' | 'locality' | 'neighbourhood'; export type GetApiV1PlacesHierarchiesArgs = {'location.place_id'?: Array | undefined, country?: Array | undefined, level?: BaseLevel | undefined, 'location.origin'?: string | undefined, offset?: number | undefined, limit?: number | undefined}; export type GetApiV1PlacesHierarchiesOptions = {baseUrl?: string | undefined, BearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const baseLevel = z.enum(["planet", "continent", "country", "region", "county", "localadmin", "locality", "neighbourhood"]); export const hierarchyDetails = z.object({type: baseLevel, place_id: z.string()}); export const hierarchiesResponse = z.object({count: z.number().int(), next: z.string().nullable().optional(), previous: z.string().nullable().optional(), place_hierarchies: z.array(z.array(hierarchyDetails))}); 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 Place Hierarchies * * GET /v1/places/hierarchies */ export const getApiV1PlacesHierarchies = async (args: GetApiV1PlacesHierarchiesArgs, options?: GetApiV1PlacesHierarchiesOptions) => { const {baseUrl = "https://api.predicthq.com", fetch: fetchFn = fetch, BearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args['location.place_id'] != null) query.append("location.place_id", args['location.place_id'].join(',')) for (const item of args.country ?? []) query.append("country", String(item)) if (args.level != null) query.append("level", String(args.level)) if (args['location.origin'] != null) query.append("location.origin", String(args['location.origin'])) if (args.offset != null) query.append("offset", String(args.offset)) if (args.limit != null) query.append("limit", String(args.limit)) if (BearerAuth !== undefined) headers.set('authorization', `Bearer ${BearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/places/hierarchies${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(hierarchiesResponse, await res.json()) };