import {z} from 'zod' export type GetApiReviewsFormatArgs = {isbn?: number | undefined, title?: string | undefined, author?: string | undefined, 'api-key'?: string | undefined}; export type GetApiReviewsFormatOptions = {baseUrl?: string | undefined, apiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const getApiReviewsFormatResponse = z.object({status: z.string().optional(), copyright: z.string().optional(), num_results: z.number().int().optional(), results: z.array(z.object({url: z.string().optional(), publication_dt: z.string().optional(), byline: z.string().optional(), book_title: z.string().optional(), book_author: z.string().optional(), summary: z.string().optional(), isbn13: z.array(z.string()).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 }; /** * Reviews * * GET /reviews.{format} */ export const getApiReviewsFormat = async (args: GetApiReviewsFormatArgs, options?: GetApiReviewsFormatOptions) => { const {baseUrl = "https://api.nytimes.com/svc/books/v3", fetch: fetchFn = fetch, apiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.isbn != null) query.append("isbn", String(args.isbn)) if (args.title != null) query.append("title", String(args.title)) if (args.author != null) query.append("author", String(args.author)) if (args['api-key'] != null) query.append("api-key", String(args['api-key'])) if (apiKey !== undefined) query.set("api-key", apiKey) const url = `${baseUrl.replace(/\/+$/, '')}/reviews.${encodeURIComponent(String(args.format))}${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(getApiReviewsFormatResponse, await res.json()) };