import {z} from 'zod' export type QueryConfigSchema = {table: string, fields: Array, filters?: (Array> | null) | undefined, aggregations?: ({[key: string]: string} | null) | undefined, groupBy?: (Array | null) | undefined, temporalGrouping?: ({[key: string]: 'hour' | 'day' | 'week' | 'month' | 'quarter' | 'year'} | null) | undefined, orderBy?: ({[key: string]: string} | null) | undefined}; export type QueryExecutionSchema = {page?: (number | null) | undefined, perPage?: (number | null) | undefined, sortBy?: (string | null) | undefined, sortDirection?: ('asc' | 'desc' | null) | undefined, locationId?: (string | null) | undefined, queryConfig: QueryConfigSchema, chartType?: (string | null) | undefined, search?: (string | null) | undefined, tz: string}; export type CreateApiAnalyticsWidgetsExecuteQueryArgs = {TENANT: string, 'API-KEY': string, body: QueryExecutionSchema}; export type CreateApiAnalyticsWidgetsExecuteQueryOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const queryResultSchema = z.object({data: z.array(z.object({})), totalCount: z.number().int(), executionTimeMs: z.number(), metadata: z.object({}).nullable().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 }; /** * Execute Query * * POST /analytics/widgets/execute-query */ export const createApiAnalyticsWidgetsExecuteQuery = async (args: CreateApiAnalyticsWidgetsExecuteQueryArgs, options: CreateApiAnalyticsWidgetsExecuteQueryOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args.TENANT != null) headers.set("TENANT", String(args.TENANT)) if (args['API-KEY'] != null) headers.set("API-KEY", String(args['API-KEY'])) const url = `${baseUrl.replace(/\/+$/, '')}/analytics/widgets/execute-query${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(queryResultSchema, await res.json()) };