import {z} from 'zod' export type GetApiMetricsArgs = {search?: string | undefined, category?: ('Cases' | 'Testing' | 'Healthcare' | 'Deaths' | 'Vaccinations') | undefined, tags?: string | undefined, exact?: boolean | undefined, Accept: 'application/json'}; export type GetApiMetricsOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const metrics = z.array(z.object({last_update: z.string(), metric: z.string(), metric_name: z.string(), category: z.string(), deprecated: z.string().nullable().optional(), doc_last_modified: z.string().nullable().optional(), tags: z.array(z.string())})); 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 }; /** * Metric search * * GET /metrics */ export const getApiMetrics = async (args: GetApiMetricsArgs, options?: GetApiMetricsOptions) => { const {baseUrl = "https://api.coronavirus.data.gov.uk/generic", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.search != null) query.append("search", String(args.search)) if (args.category != null) query.append("category", String(args.category)) if (args.tags != null) query.append("tags", String(args.tags)) if (args.exact != null) query.append("exact", String(args.exact)) if (args.Accept != null) headers.set("Accept", String(args.Accept)) const url = `${baseUrl.replace(/\/+$/, '')}/metrics${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(metrics, await res.json()) };