import {z} from 'zod' export type GetApiContentSourceSectionJsonArgs = {source: 'all' | 'nyt' | 'iht', section: string, limit?: number | undefined, offset?: number | undefined}; export type GetApiContentSourceSectionJsonOptions = {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(), short_url: z.string().optional(), byline: z.string().optional(), thumbnail_standard: z.string().optional(), item_type: z.string().optional(), source: 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(), headline: z.string().optional(), des_facet: z.array(z.string()).optional(), org_facet: z.string().optional(), per_facet: z.array(z.string()).optional(), geo_facet: z.array(z.string()).optional(), blog_name: z.string().optional(), related_urls: z.array(z.object({suggested_link_text: z.string().optional(), url: z.string().optional()})).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()}); export const getApiContentSourceSectionJsonResponse = z.object({status: z.string().optional(), copyright: z.string().optional(), num_results: z.number().int().optional(), 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 }; /** * GET /content/{source}/{section}.json */ export const getApiContentSourceSectionJson = async (args: GetApiContentSourceSectionJsonArgs, options?: GetApiContentSourceSectionJsonOptions) => { const {baseUrl = "http://api.nytimes.com/svc/news/v3", fetch: fetchFn = fetch, apikey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.limit != null) query.append("limit", String(args.limit)) if (args.offset != null) query.append("offset", String(args.offset)) if (apikey !== undefined) query.set("api-key", apikey) const url = `${baseUrl.replace(/\/+$/, '')}/content/${encodeURIComponent(String(args.source))}/${encodeURIComponent(String(args.section))}.json${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(getApiContentSourceSectionJsonResponse, await res.json()) };