import {z} from 'zod' export type GetApiPriceHistoricalPricesArgs = {Authorization?: string | undefined, symbol: string, startDate: string, endDate: string, compression?: ('1MIN' | '5MIN' | '30MIN' | '1HOUR' | 'DAILY' | 'WEEKLY' | 'MONTHLY' | 'RANGE') | undefined}; export type GetApiPriceHistoricalPricesOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const getApiPriceHistoricalPricesResponse = z.object({code: z.number().int().optional(), message: z.string().optional(), data: z.array(z.object({symbol: z.string().optional(), compression: z.string().optional(), dataStartDate: z.string().optional(), dataEndDate: z.string().optional(), priceRecordHeader: z.array(z.string()).optional(), priceHistory: z.array(z.string()).optional()})).optional()}); 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 Historical Prices * * GET /price/historical-prices */ export const getApiPriceHistoricalPrices = async (args: GetApiPriceHistoricalPricesArgs, options?: GetApiPriceHistoricalPricesOptions) => { const {baseUrl = "https://uatclientapi-v2.stockal.com/client/v2", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.Authorization != null) headers.set("Authorization", String(args.Authorization)) if (args.symbol != null) query.append("symbol", String(args.symbol)) if (args.startDate != null) query.append("startDate", String(args.startDate)) if (args.endDate != null) query.append("endDate", String(args.endDate)) if (args.compression != null) query.append("compression", String(args.compression)) const url = `${baseUrl.replace(/\/+$/, '')}/price/historical-prices${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(getApiPriceHistoricalPricesResponse, await res.json()) };