import {z} from 'zod' export type GetApiV2CdnStrataSearchArgs = {q?: string | undefined, version?: ('draft' | 'published') | undefined, limit?: number | undefined, starts_with?: string | undefined, content_type?: string | undefined, token: string}; export type GetApiV2CdnStrataSearchOptions = {baseUrl?: string | undefined, ApiKeyAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const strataSearchHit = z.object({excerpt: z.string(), score: z.number(), story: z.object({id: z.number().int(), slug: z.string(), name: z.string()})}); export const strataSearchResults = z.array(strataSearchHit); export const getApiV2CdnStrataSearchResponse = z.object({results: strataSearchResults}); 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 * * GET /v2/cdn/strata/search */ export const getApiV2CdnStrataSearch = async (args: GetApiV2CdnStrataSearchArgs, options?: GetApiV2CdnStrataSearchOptions) => { const {baseUrl = "https://api.storyblok.com", fetch: fetchFn = fetch, ApiKeyAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.q != null) query.append("q", String(args.q)) if (args.version != null) query.append("version", String(args.version)) if (args.limit != null) query.append("limit", String(args.limit)) if (args.starts_with != null) query.append("starts_with", String(args.starts_with)) if (args.content_type != null) query.append("content_type", String(args.content_type)) if (args.token != null) query.append("token", String(args.token)) if (ApiKeyAuth !== undefined) query.set("token", ApiKeyAuth) const url = `${baseUrl.replace(/\/+$/, '')}/v2/cdn/strata/search${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(getApiV2CdnStrataSearchResponse, await res.json()) };