Created
February 1, 2024 22:47
-
-
Save pmbanugo/9d0e53605a7eec2650b6c85a2df5258f to your computer and use it in GitHub Desktop.
Cron Atlas: Top 5 HackerNews Stories Via Email
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export async function handler() { | |
const topStoriesUrl = "https://hacker-news.firebaseio.com/v0/topstories.json"; | |
// Fetch the top stories IDs | |
const response = await fetch(topStoriesUrl); | |
const storyIds = await response.json(); | |
const top5StoryIds = storyIds.slice(0, 5); | |
// Fetch the story details for each top story in parallel | |
const storyDetailsPromises = top5StoryIds.map((id) => | |
fetch(`https://hacker-news.firebaseio.com/v0/item/${id}.json`).then((res) => | |
res.json() | |
) | |
); | |
// Resolve all story detail promises | |
const topStories = await Promise.all(storyDetailsPromises); | |
await sendEmail(topStories); | |
} | |
async function sendEmail(stories) { | |
const emailHtml = `<html> | |
<body> | |
<h1>Top 5 Hacker News Stories</h1> | |
<ol> | |
${stories | |
.map((story) => `<li><a href="${story.url}">${story.title}</a></li>`) | |
.join("")} | |
</ol> | |
</body> | |
</html>`; | |
const emailUrl = `https://api.resend.com/emails`; | |
const emailHeaders = { | |
Authorization: `Bearer ${process.env.RESEND_API_KEY}`, | |
"Content-Type": "application/json", | |
}; | |
const emailBody = JSON.stringify({ | |
to: process.env.EMAIL_RECIPIENT, | |
from: "[email protected]", | |
subject: "Top 5 Hacker News Stories Roundup", | |
html: emailHtml, | |
}); | |
const emailResponse = fetch(emailUrl, { | |
method: "POST", | |
headers: emailHeaders, | |
body: emailBody, | |
}).then((res) => { | |
if (res.ok) { | |
console.log("Email sent successfully"); | |
return res.json(); | |
} | |
throw new Error("Error sending email"); | |
}); | |
return emailResponse; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment