import {z} from 'zod' export type GetApiSectionFormatArgs = {section: 'home' | 'opinion' | 'world' | 'national' | 'politics' | 'upshot' | 'nyregion' | 'business' | 'technology' | 'science' | 'health' | 'sports' | 'arts' | 'books' | 'movies' | 'theater' | 'sundayreview' | 'fashion' | 'tmagazine' | 'food' | 'travel' | 'magazine' | 'realestate' | 'automobiles' | 'obituaries' | 'insider', format: 'json' | 'jsonp', callback?: string | undefined}; export type GetApiSectionFormatOptions = {baseUrl?: string | undefined, apikey?: string | undefined, fetch?: typeof fetch | undefined}; export const article = z.object({section: z.string().optional(), subsection: z.string().optional(), title: z.string().optional(), abstract: z.string().optional(), url: z.string().optional(), thumbnail_standard: z.string().optional(), short_url: z.string().optional(), byline: z.string().optional(), item_type: z.string().optional(), updated_date: z.string().optional(), created_date: z.string().optional(), published_date: z.string().optional(), material_type_facet: z.string().optional(), kicker: z.string().optional(), des_facet: z.array(z.string()).optional(), org_facet: z.array(z.string()).optional(), per_facet: z.array(z.string()).optional(), geo_facet: z.array(z.string()).optional(), multimedia: z.array(z.object({url: z.string().optional(), format: z.string().optional(), height: z.number().int().optional(), width: z.number().int().optional(), type: z.string().optional(), subtype: z.string().optional(), caption: z.string().optional(), copyright: z.string().optional()})).optional(), related_urls: z.array(z.object({suggested_link_text: z.string().optional(), url: z.string().optional()})).optional()}); export const getApiSectionFormatResponse = z.object({results: z.array(article).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 }; /** * Top Stories * * GET /{section}.{format} */ export const getApiSectionFormat = async (args: GetApiSectionFormatArgs, options?: GetApiSectionFormatOptions) => { const {baseUrl = "http://api.nytimes.com/svc/topstories/v2", fetch: fetchFn = fetch, apikey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.callback != null) query.append("callback", String(args.callback)) if (apikey !== undefined) query.set("api-key", apikey) const url = `${baseUrl.replace(/\/+$/, '')}/${encodeURIComponent(String(args.section))}.${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(getApiSectionFormatResponse, await res.json()) };