import {z} from 'zod' export type GetApiSymbolSearchArgs = {symbol: string, outputsize?: number | undefined, show_plan?: boolean | undefined}; export type GetApiSymbolSearchOptions = {baseUrl?: string | undefined, authorizationHeader?: string | undefined, fetch?: typeof fetch | undefined}; export const symbolSearchResponseItemAccess = z.object({global: z.string(), plan: z.string(), plan_business: z.string()}); export const symbolSearchResponseItem = z.object({symbol: z.string(), instrument_name: z.string(), exchange: z.string(), mic_code: z.string(), exchange_timezone: z.string(), instrument_type: z.string(), country: z.string(), currency: z.string(), access: symbolSearchResponseItemAccess.optional()}); export const getApiSymbolSearchResponse = z.object({data: z.array(symbolSearchResponseItem), status: z.string()}); 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 }; /** * Symbol search * * GET /symbol_search * * Also accepts auth: queryParameter */ export const getApiSymbolSearch = async (args: GetApiSymbolSearchArgs, options?: GetApiSymbolSearchOptions) => { const {baseUrl = "https://api.twelvedata.com", fetch: fetchFn = fetch, authorizationHeader} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.symbol != null) query.append("symbol", String(args.symbol)) if (args.outputsize != null) query.append("outputsize", String(args.outputsize)) if (args.show_plan != null) query.append("show_plan", String(args.show_plan)) if (authorizationHeader !== undefined) headers.set("Authorization", authorizationHeader) const url = `${baseUrl.replace(/\/+$/, '')}/symbol_search${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(getApiSymbolSearchResponse, await res.json()) };