import {z} from 'zod' export type OrderBy = 'asc' | 'desc'; export type FilterOperator = '=' | '!=' | '>' | '>=' | '<' | '<=' | 'in'; export type ResampleFunction = 'mean' | 'sum' | 'min' | 'max' | 'count' | 'stddev' | 'variance'; export type ReturnFormat = 'json' | 'csv'; export type JSONSchema = 'array-of-objects' | 'array-of-arrays'; export type GetApiDatasetsDatasetIdQueryArgs = {dataset_id: string, api_key?: (string | null) | undefined, order?: (OrderBy | null) | undefined, filter_column?: (string | null) | undefined, filter_value?: (number | number | string | null) | undefined, filter_operator?: (FilterOperator | null) | undefined, limit?: (number | null) | undefined, page?: number | undefined, page_size?: (number | null) | undefined, columns?: (Array | string | null) | undefined, cursor?: (string | null) | undefined, timezone?: (string | null) | undefined, time?: (string | string | null) | undefined, time_comparison?: ('=' | '>' | '>=' | '<' | '<=' | null) | undefined, start_time?: (string | string | null) | undefined, end_time?: (string | string | null) | undefined, publish_time?: (string | string | null) | undefined, publish_time_start?: (string | string | null) | undefined, publish_time_end?: (string | string | null) | undefined, resample_frequency?: (string | null) | undefined, resample_by?: (Array | string | null) | undefined, resample_function?: (ResampleFunction | null) | undefined, return_format?: ReturnFormat | undefined, download?: boolean | undefined, json_schema?: JSONSchema | undefined, 'x-api-key'?: (string | null) | undefined}; export type GetApiDatasetsDatasetIdQueryOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const metadataResponse = z.object({page: z.number().int(), limit: z.number().int().nullable(), page_size: z.number().int().nullable(), hasNextPage: z.boolean().nullable(), cursor: z.string().nullable()}); export const columnResponse = z.object({name: z.string(), type: z.string(), is_numeric: z.boolean(), is_date: z.boolean().optional(), is_datetime: z.boolean()}); export const datasetStatusEnum = z.enum(["retired", "active", "deprecated"]); export const datasetResponse = z.object({id: z.string(), name: z.string(), description: z.string().nullable(), earliest_available_time_utc: z.string().nullable(), latest_available_time_utc: z.string().nullable(), source: z.string().nullable(), last_checked_time_utc: z.string().nullable(), primary_key_columns: z.array(z.string()).nullable(), publish_time_column: z.string().nullable(), time_index_column: z.string().nullable(), subseries_index_column: z.string().nullable(), all_columns: z.array(columnResponse).nullable(), number_of_rows_approximate: z.number().int().nullable(), table_type: z.string().nullable(), is_in_snowflake: z.boolean().nullable(), data_frequency: z.string().nullable(), source_url: z.string().nullable(), publication_frequency: z.string().nullable(), is_published: z.boolean().nullable(), created_at_utc: z.string().nullable(), status: datasetStatusEnum.nullable(), popularity_rank: z.number().int().nullable().optional(), is_in_clickhouse: z.boolean().nullable().optional()}); export const queryDatasetResponse = z.object({status_code: z.number().int(), data: z.array(z.record(z.string(), z.unknown())), meta: metadataResponse, dataset_metadata: datasetResponse}); export const fileResponseData = z.object({media_type: z.string(), content: z.union([z.string(), z.string()])}); export const cSVResponse = z.object({file: fileResponseData.nullable().optional(), content_type: z.string().optional()}); export const getApiDatasetsDatasetIdQueryResponse = z.union([queryDatasetResponse, cSVResponse]); 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 }; /** * Query Dataset * * GET /datasets/{dataset_id}/query */ export const getApiDatasetsDatasetIdQuery = async (args: GetApiDatasetsDatasetIdQueryArgs, options?: GetApiDatasetsDatasetIdQueryOptions) => { const {baseUrl = "https://api.gridstatus.io/v1", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.api_key != null) query.append("api_key", String(args.api_key)) if (args.order != null) query.append("order", String(args.order)) if (args.filter_column != null) query.append("filter_column", String(args.filter_column)) if (args.filter_value != null) query.append("filter_value", String(args.filter_value)) if (args.filter_operator != null) query.append("filter_operator", String(args.filter_operator)) if (args.limit != null) query.append("limit", String(args.limit)) if (args.page != null) query.append("page", String(args.page)) if (args.page_size != null) query.append("page_size", String(args.page_size)) if (args.columns != null) query.append("columns", String(args.columns)) if (args.cursor != null) query.append("cursor", String(args.cursor)) if (args.timezone != null) query.append("timezone", String(args.timezone)) if (args.time != null) query.append("time", String(args.time)) if (args.time_comparison != null) query.append("time_comparison", String(args.time_comparison)) if (args.start_time != null) query.append("start_time", String(args.start_time)) if (args.end_time != null) query.append("end_time", String(args.end_time)) if (args.publish_time != null) query.append("publish_time", String(args.publish_time)) if (args.publish_time_start != null) query.append("publish_time_start", String(args.publish_time_start)) if (args.publish_time_end != null) query.append("publish_time_end", String(args.publish_time_end)) if (args.resample_frequency != null) query.append("resample_frequency", String(args.resample_frequency)) if (args.resample_by != null) query.append("resample_by", String(args.resample_by)) if (args.resample_function != null) query.append("resample_function", String(args.resample_function)) if (args.return_format != null) query.append("return_format", String(args.return_format)) if (args.download != null) query.append("download", String(args.download)) if (args.json_schema != null) query.append("json_schema", String(args.json_schema)) if (args['x-api-key'] != null) headers.set("x-api-key", String(args['x-api-key'])) const url = `${baseUrl.replace(/\/+$/, '')}/datasets/${encodeURIComponent(String(args.dataset_id))}/query${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(getApiDatasetsDatasetIdQueryResponse, await res.json()) };