import {z} from 'zod' export type GetApiV1QuotesLatestArgs = {filter_symbol_id?: string | undefined, filter_exchange_id?: string | undefined, limit?: number | undefined}; export type GetApiV1QuotesLatestOptions = {baseUrl?: string | undefined, APIKey?: string | undefined, fetch?: typeof fetch | undefined}; export const v1Quote = z.object({symbol_id: z.string().nullable().optional(), time_exchange: z.string().optional(), time_coinapi: z.string().optional(), ask_price: z.number().nullable().optional(), ask_size: z.number().nullable().optional(), bid_price: z.number().nullable().optional(), bid_size: z.number().nullable().optional()}); export const getApiV1QuotesLatestResponse = z.array(v1Quote); 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 }; /** * Latest data * * GET /v1/quotes/latest * * Also accepts auth: JWT */ export const getApiV1QuotesLatest = async (args: GetApiV1QuotesLatestArgs, options?: GetApiV1QuotesLatestOptions) => { const {baseUrl = "https://rest.coinapi.io", fetch: fetchFn = fetch, APIKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.filter_symbol_id != null) query.append("filter_symbol_id", String(args.filter_symbol_id)) if (args.filter_exchange_id != null) query.append("filter_exchange_id", String(args.filter_exchange_id)) if (args.limit != null) query.append("limit", String(args.limit)) if (APIKey !== undefined) headers.set("Authorization", APIKey) const url = `${baseUrl.replace(/\/+$/, '')}/v1/quotes/latest${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(getApiV1QuotesLatestResponse, await res.json()) };