Added sample code for querying the HN API in node. I used node because it takes me much less time but many other languages would work. I wanted to demonstrate the ease of hackernews API.

In order to use, install node.
Run npm install in the repo to generate the node_modules folder.
run node index.js
You should see the HN top stories logged out.
This commit is contained in:
Robert Webb 2019-02-01 23:26:16 -08:00
parent e224e68ca2
commit 5d685051b5
4 changed files with 74 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
node_modules/

42
index.js Normal file
View File

@ -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();

13
package-lock.json generated Normal file
View File

@ -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=="
}
}
}

18
package.json Normal file
View File

@ -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"
}
}