import {z} from 'zod' export type DateTruncUnit = 'year' | 'month' | 'week' | 'day' | 'hour' | 'minute' | 'second'; export type DatePartUnit = 'year' | 'month' | 'week' | 'day' | 'dayOfWeek' | 'dayOfYear' | 'hour' | 'minute' | 'second'; export type GroupByField = {field: string, alias?: (string | null) | undefined, date_trunc?: (DateTruncUnit | null) | undefined, date_part?: (DatePartUnit | null) | undefined}; export type AggregationFunction = 'count' | 'count_distinct' | 'sum' | 'avg' | 'min' | 'max' | 'first' | 'last' | 'push' | 'add_to_set'; export type AggregationOperation = {function: AggregationFunction, field?: (string | null) | undefined, alias: string, distinct_field?: (string | null) | undefined}; export type HavingCondition = {field: string, operator: string, value: number | number | string}; export type RangeBucket = {field: string, boundaries: Array, default_bucket?: (string | null) | undefined}; export type DocumentAggregationRequest = {group_by?: Array | undefined, aggregations: Array, filters?: ({[key: string]: unknown} | null) | undefined, having?: (Array | null) | undefined, unwind?: (string | null) | undefined, range_buckets?: (Array | null) | undefined, sort_by?: (string | null) | undefined, sort_direction?: string | undefined, limit?: (number | null) | undefined}; export type CreateApiV1CollectionsCollectionIdentifierDocumentsAggregateArgs = {collection_identifier: string, body: DocumentAggregationRequest}; export type CreateApiV1CollectionsCollectionIdentifierDocumentsAggregateOptions = {baseUrl?: string | undefined, BearerAuth?: string | undefined, NamespaceHeader?: string | undefined, fetch?: typeof fetch | undefined}; export const aggregationResult = z.object({group: z.record(z.string(), z.unknown()), metrics: z.record(z.string(), z.unknown())}); export const documentAggregationResponse = z.object({results: z.array(aggregationResult), total_groups: z.number().int(), query_info: z.record(z.string(), z.unknown()).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 }; /** * Aggregate Documents * * POST /v1/collections/{collection_identifier}/documents/aggregate */ export const createApiV1CollectionsCollectionIdentifierDocumentsAggregate = async (args: CreateApiV1CollectionsCollectionIdentifierDocumentsAggregateArgs, options?: CreateApiV1CollectionsCollectionIdentifierDocumentsAggregateOptions) => { const {baseUrl = "https://api.mixpeek.com", fetch: fetchFn = fetch, BearerAuth, NamespaceHeader} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (BearerAuth !== undefined) headers.set('authorization', `Bearer ${BearerAuth}`) if (NamespaceHeader !== undefined) headers.set("X-Namespace", NamespaceHeader) const url = `${baseUrl.replace(/\/+$/, '')}/v1/collections/${encodeURIComponent(String(args.collection_identifier))}/documents/aggregate${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(documentAggregationResponse, await res.json()) };