import {z} from 'zod' export type GetApiProductsSearchProductsV2Args = {query: string, pagination?: ({limit?: number | undefined, offset?: number | undefined}) | undefined, filter_by?: string | undefined}; export type GetApiProductsSearchProductsV2Options = {baseUrl?: string | undefined, apiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const getApiProductsSearchProductsV2Response = z.object({found: z.number(), hits: z.array(z.object({document: z.object({id: z.string(), title: z.string(), description: z.string(), sku: z.string(), category: z.string(), sub_category: z.string(), material: z.string(), manufacturer: z.string(), weight: z.string(), weight_grams: z.number(), purity: z.string(), premium_calculation_type: z.string(), certificate_provider: z.string().optional(), attributes: z.array(z.number()).optional(), variants: z.array(z.string()).optional(), images: z.array(z.string()).optional(), listing_id: z.string().optional(), listing_price: z.number().optional(), listing_spot_premium: z.number().optional(), listing_spot_premium_dollar: z.number().optional(), listing_expires_at: z.string().optional(), offer_id: z.string().optional(), offer_price: z.number().optional(), offer_spot_premium: z.number().optional(), offer_spot_premium_dollar: z.number().optional(), offer_expires_at: z.string().optional(), is_stocked_by_bb_store: z.boolean().optional(), is_certified: z.boolean().optional(), is_esg: z.boolean().optional(), is_ira: z.boolean().optional(), is_numismatic: z.boolean().optional(), has_listing: z.boolean().optional(), has_offer: z.boolean().optional(), favorite_count: z.number().optional(), view_count: z.number(), created_at: z.string().optional(), updated_at: z.string().optional()}), highlights: z.array(z.object({field: z.string(), snippet: z.string().optional(), matched_tokens: z.union([z.array(z.string()), z.array(z.array(z.string()))])})).optional(), text_match: z.number().optional(), text_match_info: z.object({best_field_score: z.string().optional(), best_field_weight: z.number().optional(), fields_matched: z.number().optional(), score: z.string().optional(), tokens_matched: z.number().optional()}).optional()})).optional(), facet_counts: z.array(z.object({field_name: z.string(), counts: z.array(z.object({value: z.string(), count: z.number(), highlighted: z.string().optional()})), stats: z.object({min: z.number().optional(), max: z.number().optional(), sum: z.number().optional(), avg: z.number().optional(), total_values: z.number().optional()}).optional()})).optional(), page: z.number().optional(), out_of: z.number().optional(), search_time_ms: z.number().optional(), request_params: z.object({collection_name: z.string().optional(), per_page: z.number().optional(), q: z.string().optional()}).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 }; /** * Search products * * GET /products/search-products/v2 */ export const getApiProductsSearchProductsV2 = async (args: GetApiProductsSearchProductsV2Args, options?: GetApiProductsSearchProductsV2Options) => { const {baseUrl = "https://api.collectpure.com", fetch: fetchFn = fetch, apiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.query != null) query.append("query", String(args.query)) if (args.pagination != null) query.append("pagination", JSON.stringify(args.pagination)) if (args.filter_by != null) query.append("filter_by", String(args.filter_by)) if (apiKey !== undefined) headers.set("x-api-key", apiKey) const url = `${baseUrl.replace(/\/+$/, '')}/products/search-products/v2${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(getApiProductsSearchProductsV2Response, await res.json()) };