-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathindex.mjs
70 lines (56 loc) · 1.88 KB
/
index.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import log from 'barelog'
import timestring from 'timestring'
let previousTopStoryId = null
const refreshInterval = timestring(process.env.REFRESH_INTERVAL ? process.env.REFRESH_INTERVAL : '5m', 'ms')
log(`Starting HackerNews top story tracker. A refresh will be performed every ${refreshInterval}ms`)
async function doFetch (url) {
const { signal } = new AbortController()
const timeout = setTimeout(() => signal.abort(), 10000)
try {
const res = await fetch(url, {
signal
})
if (res.ok) {
return res.json()
} else {
const text = await res.text()
throw new Error(`Fetching URL ${url}. Response status code: ${res.status}. Response body: "${text}"`)
}
} catch (e) {
throw e
} finally {
clearTimeout(timeout)
}
}
function getTopStoryId () {
return doFetch('https://hacker-news.firebaseio.com/v0/topstories.json').then((json) => json[0])
}
function getStoryDetails (id) {
return doFetch(`https://hacker-news.firebaseio.com/v0/item/${id}.json?print=pretty`)
}
async function refreshTopStory () {
try {
const topStoryId = await getTopStoryId()
if (topStoryId === previousTopStoryId) {
log('Top story is unchanged since last refresh')
} else {
const topStoryDetails = await getStoryDetails(topStoryId)
// Record this top story ID to avoid reprinting it if it remains top
previousTopStoryId = topStoryDetails.id
log(`The latest top story is:\n${topStoryDetails.title} (${topStoryDetails.url})`)
}
} catch (e) {
log('Error refreshing top story:')
log(e)
} finally {
log(`Next refresh queued for ${new Date(Date.now() + refreshInterval).toISOString()}`)
setTimeout(refreshTopStory, refreshInterval)
}
}
['SIGINT', 'SIGTERM'].forEach((sig) => {
process.on(sig, (s) => {
log(`Process received ${s} signal. Exiting...`)
process.exit(0)
})
})
refreshTopStory()