blob: 49fd0c333a7fefbea78e5eac767f8a61ea81359c (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
const story = (path: string) => `https://node-hnapi.herokuapp.com/${path}`;
const user = (path: string) => `https://hacker-news.firebaseio.com/v0/${path}.json`;
export default async function fetchAPI(path: string) {
const url = path.startsWith('user') ? user(path) : story(path);
const headers = { 'User-Agent': 'chrome' };
try {
let response = await fetch(url, { headers });
let text = await response.text();
try {
if (text === null) {
return { error: 'Not found' };
}
return JSON.parse(text);
} catch (e) {
console.error(`Received from API: ${text}`);
console.error(e);
return { error: e };
}
} catch (error) {
return { error };
}
}
|