import {z} from 'zod' export type SizeEnum = 's' | 'm' | 'l' | 'xl'; export type GetApiV1DemandSurgeArgs = {min_surge_intensity: SizeEnum, date_from: string, 'location.place_id'?: Array | undefined, 'location.origin'?: Array | undefined, 'location.radius'?: string | undefined}; export type GetApiV1DemandSurgeOptions = {baseUrl?: string | undefined, BearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const surgeDate = z.object({date: z.string(), phq_attendance_sum: z.number().int()}); export const demandSurgeResponse = z.object({count: z.number().int(), surge_dates: z.array(surgeDate).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 Demand Surges * * GET /v1/demand-surge/ */ export const getApiV1DemandSurge = async (args: GetApiV1DemandSurgeArgs, options?: GetApiV1DemandSurgeOptions) => { 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.min_surge_intensity != null) query.append("min_surge_intensity", String(args.min_surge_intensity)) if (args.date_from != null) query.append("date_from", String(args.date_from)) if (args['location.place_id'] != null) query.append("location.place_id", args['location.place_id'].join(',')) if (args['location.origin'] != null) query.append("location.origin", args['location.origin'].join(',')) if (args['location.radius'] != null) query.append("location.radius", String(args['location.radius'])) if (BearerAuth !== undefined) headers.set('authorization', `Bearer ${BearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/demand-surge/${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(demandSurgeResponse, await res.json()) };