Skip to content

Instantly share code, notes, and snippets.

@wong2
Created December 30, 2021 07:47
Show Gist options
  • Save wong2/fe283ab4636678c3d3d7958a320a3d23 to your computer and use it in GitHub Desktop.
Save wong2/fe283ab4636678c3d3d7958a320a3d23 to your computer and use it in GitHub Desktop.
addEventListener("fetch", event => {
event.respondWith(handleRequest(event.request))
})
function jsonResponse(o) {
return new Response(JSON.stringify(o), {
headers: {
"content-type": "application/json;charset=UTF-8",
'Access-Control-Allow-Origin': '*',
}
})
}
async function queryHNPoints(link) {
const url = new URL('https://hn.algolia.com/api/v1/search')
url.searchParams.append('query', link)
const resp = await fetch(url).then(r => r.json())
let total = 0
for (const h of resp.hits) {
if (!h._tags.includes('comment')) {
total += h.points || 0
}
}
return total
}
async function handleRequest(request) {
const { searchParams } = new URL(request.url)
const url = searchParams.get('url')
if (!url) {
return jsonResponse({ error: 'please query with url' })
}
const points = await queryHNPoints(url)
return jsonResponse({ url, points })
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment