import {z} from 'zod' export type GetApiSelectArgs = {q?: string | undefined, fq?: string | undefined, fl?: string | undefined, start?: number | undefined, rows?: number | undefined, wt?: ('json' | 'xml' | 'csv') | undefined}; export type GetApiSelectOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const solrResponse = z.object({responseHeader: z.object({zkConnected: z.boolean().optional(), status: z.number().int().optional(), QTime: z.number().int().optional(), params: z.object({}).optional()}).optional(), response: z.object({numFound: z.number().int().optional(), start: z.number().int().optional(), maxScore: z.number().optional(), docs: z.array(z.object({})).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 }; /** * Apache Solr powered search * * GET /select */ export const getApiSelect = async (args: GetApiSelectArgs, options?: GetApiSelectOptions) => { const {baseUrl = "https://api.ideaconsult.net/nanoreg1", fetch: fetchFn = fetch} = 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.fq != null) query.append("fq", String(args.fq)) if (args.fl != null) query.append("fl", String(args.fl)) if (args.start != null) query.append("start", String(args.start)) if (args.rows != null) query.append("rows", String(args.rows)) if (args.wt != null) query.append("wt", String(args.wt)) const url = `${baseUrl.replace(/\/+$/, '')}/select${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(solrResponse, await res.json()) };