import {z} from 'zod' export type GetApiApiV2NewsIdArgs = {id: string}; export type GetApiApiV2NewsIdOptions = {baseUrl?: string | undefined, Bearer?: string | undefined, fetch?: typeof fetch | undefined}; export const newsImage = z.object({url: z.string(), smallUrl: z.string(), width: z.number().int(), height: z.number().int(), alt: z.string(), source: z.enum(["commons", "ai"]), credit: z.string().nullable(), license: z.string().nullable(), licenseUrl: z.string().nullable(), sourceUrl: z.string().nullable()}).nullable(); export const newsAsset = z.object({ticker: z.string(), tickers: z.array(z.string()), name: z.string(), type: z.enum(["stock", "fii", "fiagro", "fiinfra", "fidc", "fip", "etf", "bdr", "index", "currency"]), relevance: z.enum(["primary", "secondary"]), sentiment: z.enum(["positive", "negative", "neutral"]).nullable(), reason: z.string().nullable()}); export const newsSource = z.object({name: z.string(), title: z.string(), url: z.string(), publishedAt: z.string()}); export const newsRelatedStory = z.object({id: z.string(), slug: z.string(), title: z.string(), description: z.string().nullable(), image: newsImage, eventType: z.enum(["earnings", "dividends", "guidance", "mna", "financing", "buyback", "rating", "analyst", "management", "legal_regulatory", "operations", "market_move", "macro", "other"]), scope: z.enum(["company", "market"]), publishedAt: z.string(), sentiment: z.enum(["positive", "negative", "neutral", "mixed"]), importance: z.number().int().gte(1).lte(5), tickers: z.array(z.string()), sourceCount: z.number().int()}); export const newsStoryDetail = z.object({id: z.string(), slug: z.string(), url: z.string(), title: z.string(), description: z.string().nullable(), summary: z.string(), image: newsImage, keyPoints: z.array(z.string()), article: z.string().nullable(), eventType: z.enum(["earnings", "dividends", "guidance", "mna", "financing", "buyback", "rating", "analyst", "management", "legal_regulatory", "operations", "market_move", "macro", "other"]), scope: z.enum(["company", "market"]), sentiment: z.object({label: z.enum(["positive", "negative", "neutral", "mixed"]), score: z.number()}), importance: z.number().int().gte(1).lte(5), topics: z.array(z.string()), assets: z.array(newsAsset), sources: z.array(newsSource), publishedAt: z.string(), updatedAt: z.string(), articleWrittenAt: z.string().nullable(), related: z.array(newsRelatedStory)}); export const newsDetailResponse = z.object({results: z.array(newsStoryDetail), requestedAt: z.string(), took: z.number().int().gte(0)}); 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 }; /** * Notícia * * GET /api/v2/news/{id} */ export const getApiApiV2NewsId = async (args: GetApiApiV2NewsIdArgs, options?: GetApiApiV2NewsIdOptions) => { const {baseUrl = "https://brapi.dev", fetch: fetchFn = fetch, Bearer} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (Bearer !== undefined) headers.set('authorization', `Bearer ${Bearer}`) const url = `${baseUrl.replace(/\/+$/, '')}/api/v2/news/${encodeURIComponent(String(args.id))}${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(newsDetailResponse, await res.json()) };