import {z} from 'zod' export type GetApiServicesArgs = {q?: string | undefined, tags?: string | undefined, page?: number | undefined, limit?: number | undefined}; export type GetApiServicesOptions = {baseUrl?: string | undefined, ApiKeyAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const doc = z.object({type: z.string().optional(), slug: z.string().optional(), title: z.string().optional(), summary: z.string().optional(), url: z.string().optional(), tags: z.array(z.string()).optional(), date: z.string().optional(), content: z.string().optional()}).and(z.record(z.string(), z.unknown())); export const pagedEnvelope = z.object({meta: z.object({total: z.number().int().optional(), page: z.number().int().optional(), limit: z.number().int().optional(), pages: z.number().int().optional(), query: z.record(z.string(), z.unknown()).optional()}).optional(), data: z.array(doc).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 }; /** * Services * * GET /services */ export const getApiServices = async (args: GetApiServicesArgs, options?: GetApiServicesOptions) => { const {baseUrl = "https://api.apievangelist.com/v1", 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.tags != null) query.append("tags", String(args.tags)) if (args.page != null) query.append("page", String(args.page)) if (args.limit != null) query.append("limit", String(args.limit)) if (ApiKeyAuth !== undefined) headers.set("x-api-key", ApiKeyAuth) const url = `${baseUrl.replace(/\/+$/, '')}/services${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(pagedEnvelope, await res.json()) };