diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..40b878d --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +node_modules/ \ No newline at end of file diff --git a/index.js b/index.js new file mode 100644 index 0000000..0d06468 --- /dev/null +++ b/index.js @@ -0,0 +1,42 @@ +const fetch = require("node-fetch"); + +// implemented from: https://github.com/HackerNews/API + +const HN_PREFIX = "https://hacker-news.firebaseio.com/v0/"; + +const TOP_STORIES = "topstories"; +const ITEM = "item"; + +function hnFetch(type, id = "") { + const url = id + ? `${HN_PREFIX}${type}/${id}.json` + : `${HN_PREFIX}${type}.json`; + return fetch(url, { + method: "GET", + headers: { + "Content-Type": "application/json" + } + }) + .then(res => { + if (!isStatusOk(res.status)) { + throw res; + } + return res.json(); + }) + .then(res => res) + .catch(error => console.error(error)); +} + +function isStatusOk(statusCode) { + return statusCode === 200 || statusCode === 304; +} +async function main() { + const storyIds = await hnFetch(TOP_STORIES); + const stories = await Promise.all( + storyIds.slice(0, 20).map(storyId => hnFetch(ITEM, storyId)) + ); + + console.log(stories.map(story => { delete story.kids; return story; })); +} + +main(); diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..4ec4bc6 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,13 @@ +{ + "name": "hacker-news-cli", + "version": "1.0.0", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "node-fetch": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.3.0.tgz", + "integrity": "sha512-MOd8pV3fxENbryESLgVIeaGKrdl+uaYhCSSVkjeOb/31/njTpcis5aWfdqgNlHIrKOLRbMnfPINPOML2CIFeXA==" + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..adf3dac --- /dev/null +++ b/package.json @@ -0,0 +1,18 @@ +{ + "name": "hacker-news-cli", + "version": "1.0.0", + "description": "TODO", + "main": "index.js", + "scripts": { + "test": "mocha ." + }, + "repository": { + "type": "git", + "url": "ssh://git@irc.anarchyplanet.org:2222/notnull/hacker-news-cli.git" + }, + "author": "", + "license": "MIT", + "dependencies": { + "node-fetch": "^2.3.0" + } +}