diff options
author | 2025-06-05 14:25:23 +0000 | |
---|---|---|
committer | 2025-06-05 14:25:23 +0000 | |
commit | e586d7d704d475afe3373a1de6ae20d504f79d6d (patch) | |
tree | 7e3fa24807cebd48a86bd40f866d792181191ee9 /examples/hackernews/src/lib/api.ts | |
download | astro-e586d7d704d475afe3373a1de6ae20d504f79d6d.tar.gz astro-e586d7d704d475afe3373a1de6ae20d504f79d6d.tar.zst astro-e586d7d704d475afe3373a1de6ae20d504f79d6d.zip |
Sync from a8e1c0a7402940e0fc5beef669522b315052df1blatest
Diffstat (limited to 'examples/hackernews/src/lib/api.ts')
-rw-r--r-- | examples/hackernews/src/lib/api.ts | 24 |
1 files changed, 24 insertions, 0 deletions
diff --git a/examples/hackernews/src/lib/api.ts b/examples/hackernews/src/lib/api.ts new file mode 100644 index 000000000..49fd0c333 --- /dev/null +++ b/examples/hackernews/src/lib/api.ts @@ -0,0 +1,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 }; + } +} |