Skip to content

Instantly share code, notes, and snippets.

@pmbanugo
Created February 1, 2024 22:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pmbanugo/9d0e53605a7eec2650b6c85a2df5258f to your computer and use it in GitHub Desktop.
Save pmbanugo/9d0e53605a7eec2650b6c85a2df5258f to your computer and use it in GitHub Desktop.
Cron Atlas: Top 5 HackerNews Stories Via Email
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: "onboarding@resend.dev",
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