import {z} from 'zod' export type GetApiApiV1MacroSeriesNameArgs = {series_name: string, start?: (string | null) | undefined, end?: (string | null) | undefined, limit?: number | undefined, format?: string | undefined}; export type GetApiApiV1MacroSeriesNameOptions = {baseUrl: string, ApiKeyHeader?: string | undefined, fetch?: typeof fetch | undefined}; export const macroDataPoint = z.object({date: z.string(), value: z.number()}); export const macroSeriesResponse = z.object({series: z.string(), series_code: z.string(), count: z.number().int(), data: z.array(macroDataPoint)}); 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 Series * * GET /api/v1/macro/{series_name} */ export const getApiApiV1MacroSeriesName = async (args: GetApiApiV1MacroSeriesNameArgs, options: GetApiApiV1MacroSeriesNameOptions) => { const {baseUrl, fetch: fetchFn = fetch, ApiKeyHeader} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.start != null) query.append("start", String(args.start)) if (args.end != null) query.append("end", String(args.end)) if (args.limit != null) query.append("limit", String(args.limit)) if (args.format != null) query.append("format", String(args.format)) if (ApiKeyHeader !== undefined) headers.set("X-API-Key", ApiKeyHeader) const url = `${baseUrl.replace(/\/+$/, '')}/api/v1/macro/${encodeURIComponent(String(args.series_name))}${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(macroSeriesResponse, await res.json()) };