import {z} from 'zod' export type GetApiV1QueriesJobKeyArgs = {job_key: string, num_rows?: string | undefined}; export type GetApiV1QueriesJobKeyOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const query = z.object({job_key: z.string(), status: z.union([z.literal("running"), z.literal("completed"), z.literal("error")]), error: z.string().optional(), results: z.array(z.object({format: z.union([z.literal("csv"), z.literal("parquet"), z.literal("arrow"), z.literal("text"), z.literal("image"), z.literal("html"), z.literal("file")]), url: z.string(), name: z.string().optional(), size: z.number().optional(), mime_type: z.string().optional()})).optional(), result_preview: z.string().optional(), result_metadata: z.object({columns: z.array(z.object({name: z.string(), type: z.union([z.literal("number"), z.literal("string"), z.literal("date"), z.literal("datetime"), z.literal("boolean"), z.literal("other")])})).optional(), duration: z.number().optional(), num_rows: z.number().optional(), row_limit: z.number().optional(), byte_limit: z.number().optional()}).optional(), sql: z.string().optional()}); export const getApiV1QueriesJobKeyResponse = z.object({success: z.literal(true), request_id: z.string(), result: query}); 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 a query * * GET /v1/queries/:job_key */ export const getApiV1QueriesJobKey = async (args: GetApiV1QueriesJobKeyArgs, options?: GetApiV1QueriesJobKeyOptions) => { const {baseUrl = "https://api.app.count.co/v1", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.num_rows != null) query.append("num_rows", String(args.num_rows)) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/queries/:job_key${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(getApiV1QueriesJobKeyResponse, await res.json()) };