import {z} from 'zod' export type GetApiQueryJsonArgs = {name?: string | undefined, latitude?: string | undefined, longitude?: string | undefined, elevation?: number | undefined, sw?: string | undefined, query?: string | undefined, filter?: string | undefined, date_range?: string | undefined, facets?: (0 | 1) | undefined, sort?: string | undefined, limit?: number | undefined, offset?: number | undefined}; export type GetApiQueryJsonOptions = {baseUrl?: string | undefined, apikey?: string | undefined, fetch?: typeof fetch | undefined}; export const event = z.object({event_id: z.number().int().optional(), event_schedule_id: z.number().int().optional(), last_modified: z.string().optional(), event_name: z.string().optional(), event_detail_url: z.string().optional(), web_description: z.string().optional(), city: z.string().optional(), state: z.string().optional(), film_rating: z.boolean().optional(), critic_name: z.string().optional(), times_pick: z.boolean().optional(), free: z.boolean().optional(), kid_friendly: z.boolean().optional(), last_chance: z.boolean().optional(), festival: z.boolean().optional(), long_running_show: z.boolean().optional(), previews_and_openings: z.boolean().optional(), recurring_start_date: z.string().optional(), recur_days: z.array(z.string()).optional()}); export const getApiQueryJsonResponse = z.object({results: z.array(event).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 }; /** * Geographic API * * GET /query.json */ export const getApiQueryJson = async (args: GetApiQueryJsonArgs, options?: GetApiQueryJsonOptions) => { const {baseUrl = "http://api.nytimes.com/svc/semantic/v2/geocodes", fetch: fetchFn = fetch, apikey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.name != null) query.append("name", String(args.name)) if (args.latitude != null) query.append("latitude", String(args.latitude)) if (args.longitude != null) query.append("longitude", String(args.longitude)) if (args.elevation != null) query.append("elevation", String(args.elevation)) if (args.sw != null) query.append("sw", String(args.sw)) if (args.query != null) query.append("query", String(args.query)) if (args.filter != null) query.append("filter", String(args.filter)) if (args.date_range != null) query.append("date_range", String(args.date_range)) if (args.facets != null) query.append("facets", String(args.facets)) if (args.sort != null) query.append("sort", String(args.sort)) if (args.limit != null) query.append("limit", String(args.limit)) if (args.offset != null) query.append("offset", String(args.offset)) if (apikey !== undefined) query.set("api-key", apikey) const url = `${baseUrl.replace(/\/+$/, '')}/query.json${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(getApiQueryJsonResponse, await res.json()) };