import {z} from 'zod' export type GetApiQodArgs = {category?: unknown | undefined, language?: unknown | undefined, id?: unknown | undefined}; export type GetApiQodOptions = {baseUrl?: string | undefined, BearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const qOD = z.object({author: z.string().optional(), quote: z.string(), tags: z.array(z.string()).optional(), id: z.string(), image: z.string().optional(), length: z.number().int().optional(), date: z.string(), title: z.string().optional()}); export const qODResponse = z.object({success: z.string().optional(), contents: z.object({quotes: z.array(qOD).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 }; /** * Gets `Quote of the Day` (QOD). Optional `category` param determines the category of returned quote of the day * * GET /qod */ export const getApiQod = async (args: GetApiQodArgs, options?: GetApiQodOptions) => { const {baseUrl = "https://quotes.rest", fetch: fetchFn = fetch, BearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.category != null) query.append("category", String(args.category)) if (args.language != null) query.append("language", String(args.language)) if (args.id != null) query.append("id", String(args.id)) if (BearerAuth !== undefined) headers.set('authorization', `Bearer ${BearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/qod${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(qODResponse, await res.json()) };