-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNewsApi.ts
49 lines (37 loc) · 1.26 KB
/
NewsApi.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import { newsApiKey } from "./ApiKey";
import axios from "axios";
// Endpoints
const apiBaseUrl = "https://newsapi.org/v2";
const breakingNewsUrl = `${apiBaseUrl}/top-headlines?country=us&apiKey=${newsApiKey}`;
const recommendedNewsUrl = `${apiBaseUrl}/top-headlines?country=us&category=business&apiKey=${newsApiKey}`;
const discoverNewsUrl = (discover) =>
`${apiBaseUrl}/top-headlines?country=us&category=${discover}&apiKey=${newsApiKey}`;
const searchNewsUrl = (query) =>
`${apiBaseUrl}/everything?q=${query}&apiKey=${newsApiKey}`;
const newsApiCall = async (endpoints, params) => {
const options = {
method: "GET",
url: endpoints,
params: params ? params : {},
};
try {
const response = await axios.request(options);
return response.data;
} catch (error) {
console.log(error);
return {};
}
};
export const fetchBreakingNews = async () => {
return await newsApiCall(breakingNewsUrl);
};
export const fetchRecommendedNews = async () => {
return await newsApiCall(recommendedNewsUrl);
};
export const fetchDiscoverNews = async (discover) => {
return await newsApiCall(discoverNewsUrl(discover));
};
export const fetchSearchNews = async (query) => {
const endpoint = searchNewsUrl(query);
return await newsApiCall(endpoint);
};