import {z} from 'zod' export type GetApiImagesSearchArgs = {term: string, limit?: number | undefined, filters?: string | undefined}; export type GetApiImagesSearchOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const getApiImagesSearchResponse = z.array(z.object({description: z.string().optional(), is_official: z.boolean().optional(), is_automated: z.boolean().optional(), name: z.string().optional(), star_count: z.number().int().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 images * * GET /images/search */ export const getApiImagesSearch = async (args: GetApiImagesSearchArgs, options: GetApiImagesSearchOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.term != null) query.append("term", String(args.term)) if (args.limit != null) query.append("limit", String(args.limit)) if (args.filters != null) query.append("filters", String(args.filters)) const url = `${baseUrl.replace(/\/+$/, '')}/images/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(getApiImagesSearchResponse, await res.json()) };