import {z} from 'zod' export type GetApiSecurityTypeMetricsArgs = {type: string, name?: string | undefined, prefer_read_replica?: boolean | undefined}; export type GetApiSecurityTypeMetricsOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const metricsSchema = z.object({data_type: z.enum(["string", "number64", "datetime64", "int64", "bool", "object"]), description: z.string(), name: z.string(), object_schema: z.object({}).optional()}); export const getApiSecurityTypeMetricsResponse = z.array(metricsSchema); 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 the metrics defined for a set of securities * * GET /security/{type}/metrics */ export const getApiSecurityTypeMetrics = async (args: GetApiSecurityTypeMetricsArgs, options?: GetApiSecurityTypeMetricsOptions) => { const {baseUrl = "https://api.merqube.com", fetch: fetchFn = fetch} = 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.prefer_read_replica != null) query.append("prefer_read_replica", String(args.prefer_read_replica)) const url = `${baseUrl.replace(/\/+$/, '')}/security/${encodeURIComponent(String(args.type))}/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(getApiSecurityTypeMetricsResponse, await res.json()) };