summaryrefslogtreecommitdiff
path: root/examples/hackernews/src/lib/api.ts
diff options
context:
space:
mode:
authorGravatar Tony Sullivan <tony.f.sullivan@outlook.com> 2022-11-01 16:20:04 +0000
committerGravatar GitHub <noreply@github.com> 2022-11-01 16:20:04 +0000
commit4e2bd173932c231697a17a3098dc22ef3e481525 (patch)
tree0cf7877436a1463d78dad231ef28ebd8116225fc /examples/hackernews/src/lib/api.ts
parentbb6e8800094dc59841eb3b345fcb8baca9e17ce9 (diff)
downloadastro-4e2bd173932c231697a17a3098dc22ef3e481525.tar.gz
astro-4e2bd173932c231697a17a3098dc22ef3e481525.tar.zst
astro-4e2bd173932c231697a17a3098dc22ef3e481525.zip
Adds a Hackernews example site (#5213)
* adds the hackernews example - TODO add readme content * refactor: moving styles from root.css into components * chore: add README content * chore: lint fixes + prettier-plugin-astro@0.4.0 * Update examples/hackernews/README.md Co-authored-by: Sarah Rainsberger <sarah@rainsberger.ca> * lint: remove unused variable * nit: adding check command to example Co-authored-by: Sarah Rainsberger <sarah@rainsberger.ca>
Diffstat (limited to 'examples/hackernews/src/lib/api.ts')
-rw-r--r--examples/hackernews/src/lib/api.ts24
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..61fc2f9ab
--- /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(`Recevied from API: ${text}`);
+ console.error(e);
+ return { error: e };
+ }
+ } catch (error) {
+ return { error };
+ }
+}