import {z} from 'zod' export type Currency = string; export type Source = string; export type RateType = 'MID' | 'BUY' | 'SELL'; export type GetApiV1RatesBaseArgs = {base: Currency, as_of?: string | undefined, source?: Source | undefined, type?: RateType | undefined, limit?: number | undefined, offset?: number | undefined}; export type GetApiV1RatesBaseOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const currency = z.string(); export const rateType = z.enum(["MID", "BUY", "SELL"]); export const source = z.string().max(50); export const exchangeRate = z.object({as_of: z.string(), fetched_at: z.string(), base: currency, target: currency, rate_type: rateType, source: source, rate: z.number()}); export const pageExchangeRate = z.object({results: z.array(exchangeRate), total: z.number().int()}); 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 rates for a base currency effective from a specific time * * GET /v1/rates/{base} */ export const getApiV1RatesBase = async (args: GetApiV1RatesBaseArgs, options: GetApiV1RatesBaseOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.as_of != null) query.append("as_of", String(args.as_of)) if (args.source != null) query.append("source", String(args.source)) if (args.type != null) query.append("type", String(args.type)) if (args.limit != null) query.append("limit", String(args.limit)) if (args.offset != null) query.append("offset", String(args.offset)) const url = `${baseUrl.replace(/\/+$/, '')}/v1/rates/${encodeURIComponent(String(args.base))}${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(pageExchangeRate, await res.json()) };