import {z} from 'zod' export type ReturnFormat = 'json' | 'csv'; export type JSONSchema = 'array-of-objects' | 'array-of-arrays'; export type GetApiDatasetsArgs = {api_key?: (string | null) | undefined, return_format?: ReturnFormat | undefined, download?: boolean | undefined, json_schema?: JSONSchema | undefined, 'x-api-key'?: (string | null) | undefined}; export type GetApiDatasetsOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; 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 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 listDatasetsDatasetMetadataResponse = z.object({resample_conversion: z.record(z.string(), z.number().int()).optional()}); export const listDatasetsResponse = z.object({status_code: z.number().int(), data: z.array(datasetResponse), meta: metadataResponse, dataset_metadata: listDatasetsDatasetMetadataResponse}); 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 }; /** * List Datasets * * GET /datasets */ export const getApiDatasets = async (args: GetApiDatasetsArgs, options?: GetApiDatasetsOptions) => { 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.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${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(listDatasetsResponse, await res.json()) };