import {z} from 'zod' export type GetApiV1GoogleNewsTrendingArgs = {hl?: string | undefined, gl?: string | undefined, max_results?: number | undefined}; export type GetApiV1GoogleNewsTrendingOptions = {baseUrl?: string | undefined, apiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const newsSource = z.object({name: z.string(), url: z.string().nullable().optional(), icon: z.string().nullable().optional()}); export const newsRelatedStory = z.object({title: z.string(), link: z.string(), source: z.string().nullable().optional(), published_at: z.string().nullable().optional()}); export const newsArticle = z.object({title: z.string(), link: z.string(), snippet: z.string().nullable().optional(), source: newsSource, published_at: z.string().nullable().optional(), thumbnail: z.string().nullable().optional(), related_stories: z.array(newsRelatedStory).optional()}); export const newsTrendingResponse = z.object({articles: z.array(newsArticle), language: z.string().optional(), country: z.string().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 }; /** * Trending news * * GET /v1/google/news/trending */ export const getApiV1GoogleNewsTrending = async (args: GetApiV1GoogleNewsTrendingArgs, options?: GetApiV1GoogleNewsTrendingOptions) => { const {baseUrl = "https://scrapebadger.com", fetch: fetchFn = fetch, apiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.hl != null) query.append("hl", String(args.hl)) if (args.gl != null) query.append("gl", String(args.gl)) if (args.max_results != null) query.append("max_results", String(args.max_results)) if (apiKey !== undefined) headers.set("x-api-key", apiKey) const url = `${baseUrl.replace(/\/+$/, '')}/v1/google/news/trending${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(newsTrendingResponse, await res.json()) };