//native
type Newsapi = {
apiKey: string
}
export async function main(
resource: Newsapi,
params: {
q?: string
searchIn?: string
sources?: string
domains?: string
excludeDomains?: string
from?: string // format: YYYY-MM-DD
to?: string // format: YYYY-MM-DD
language?:
| 'ar'
| 'de'
| 'en'
| 'es'
| 'fr'
| 'he'
| 'it'
| 'nl'
| 'no'
| 'pt'
| 'ru'
| 'sv'
| 'ud'
| 'zh'
sortBy?: 'relevancy' | 'popularity' | 'publishedAt'
pageSize?: number // max 100
page?: number
}
) {
const url = new URL('https://newsapi.org/v2/everything')
// Append the API key for authentication
url.searchParams.append('apiKey', resource.apiKey)
// Append the query parameters if provided
for (const [key, value] of Object.entries(params)) {
if (value !== undefined && value !== '') {
url.searchParams.append(key, value.toString())
}
}
const response = await fetch(url.toString(), {
method: 'GET',
headers: {
accept: 'application/json'
}
})
if (!response.ok) {
const error = await response.text()
throw new Error(`HTTP error! status: ${response.status}`)
}
const data = await response.json()
return data
}
Submitted by hugo697 536 days ago