import {z} from 'zod' export type UpdateApiQodArgs = {repeat_after?: number | undefined, authors?: unknown | undefined, title: unknown, private?: boolean | undefined, language?: unknown | undefined, sfw?: boolean | undefined}; export type UpdateApiQodOptions = {baseUrl?: string | undefined, BearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const successResponse = z.object({success: z.string().optional(), contents: z.array(z.unknown()).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 }; /** * Create a private `Quote of the Day` service. * * PUT /qod */ export const updateApiQod = async (args: UpdateApiQodArgs, options?: UpdateApiQodOptions) => { 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.repeat_after != null) query.append("repeat_after", String(args.repeat_after)) if (args.authors != null) query.append("authors", String(args.authors)) if (args.title != null) query.append("title", String(args.title)) if (args.private != null) query.append("private", String(args.private)) if (args.language != null) query.append("language", String(args.language)) if (args.sfw != null) query.append("sfw", String(args.sfw)) if (BearerAuth !== undefined) headers.set('authorization', `Bearer ${BearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/qod${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "PUT", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(successResponse, await res.json()) };