import {z} from 'zod' export type GetApiCallsIdStatsArgs = {id: string, kind: string, time: string, type: string, location_id?: string | undefined}; export type GetApiCallsIdStatsOptions = {baseUrl?: string | undefined, ApiKeyAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const getApiCallsIdStatsResponse = z.object({meta: z.object({kind: z.string().optional(), call_id: z.string().optional(), type: z.string().optional(), time: z.string().optional(), location_id: z.string().optional(), name: z.string().optional()}).optional(), stat: z.object({avg_latency: z.number().optional(), max_latency: z.number().int().optional(), time: z.string().optional(), count: z.number().int().optional()}).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 Stats for an API Call for a Specific Time Period * * GET /calls/{id}/stats/ */ export const getApiCallsIdStats = async (args: GetApiCallsIdStatsArgs, options?: GetApiCallsIdStatsOptions) => { const {baseUrl = "https://client.apimetrics.io/api/2", fetch: fetchFn = fetch, ApiKeyAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.kind != null) query.append("kind", String(args.kind)) if (args.time != null) query.append("time", String(args.time)) if (args.type != null) query.append("type", String(args.type)) if (args.location_id != null) query.append("location_id", String(args.location_id)) if (ApiKeyAuth !== undefined) headers.set("Authorization", ApiKeyAuth) const url = `${baseUrl.replace(/\/+$/, '')}/calls/${encodeURIComponent(String(args.id))}/stats/${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(getApiCallsIdStatsResponse, await res.json()) };