import {z} from 'zod' export type GetApiReviewNuggetsDataArgs = {store: string, per_page?: number | undefined, sku?: Array | undefined, min_rating?: number | undefined, types: 'store_review' | 'product_review', branch?: string | undefined, tags?: Array | undefined}; export type GetApiReviewNuggetsDataOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const reviewNuggetsResponse = z.object({id: z.number().int().optional(), type: z.string().optional(), text: z.string().optional(), rating: z.string().optional(), review_id: z.string().optional(), date_created_nugget: z.string().optional()}); export const getApiReviewNuggetsDataResponse = z.object({success: z.boolean().optional(), data: z.array(reviewNuggetsResponse).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 }; /** * Retrieve Review Nuggets * * GET /review-nuggets/data */ export const getApiReviewNuggetsData = async (args: GetApiReviewNuggetsDataArgs, options?: GetApiReviewNuggetsDataOptions) => { const {baseUrl = "https://api.reviews.io", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.store != null) query.append("store", String(args.store)) if (args.per_page != null) query.append("per_page", String(args.per_page)) for (const item of args.sku ?? []) query.append("sku", String(item)) if (args.min_rating != null) query.append("min_rating", String(args.min_rating)) if (args.types != null) query.append("types", String(args.types)) if (args.branch != null) query.append("branch", String(args.branch)) for (const item of args.tags ?? []) query.append("tags", String(item)) const url = `${baseUrl.replace(/\/+$/, '')}/review-nuggets/data${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(getApiReviewNuggetsDataResponse, await res.json()) };