Skip to content

Commit

Permalink
feat: load and show github stars for projects
Browse files Browse the repository at this point in the history
  • Loading branch information
agrmohit committed Aug 29, 2024
1 parent 3202837 commit 8a4a658
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 4 deletions.
50 changes: 50 additions & 0 deletions assets/js/script-stars.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
// Get GitHub stars and add it next to project title if stars > 0
async function GitHubStars() {
const projectArticles = document.querySelectorAll(".github-project");

for (const projectArticle of projectArticles) {
const h3 = projectArticle.querySelector("h3");
const githubURL = h3.getAttribute("data-url");
let stars = null;

if (window.location.hostname === "127.0.0.1") {
// Mock data for local development
stars = getMockStars();
} else {
stars = await getGithubStars(githubURL);
}

if (stars) {
h3.innerHTML = h3.innerHTML.trim().replace("<a", ` ${stars}⭐<a`);
}
}

function getMockStars() {
const choices = [0, 0, 4, 13, 24, 46, 50, 83, 90, 150];
return choices[Math.floor(Math.random() * choices.length)];
}

async function getGithubStars(repoURL) {
const url = new URL(repoURL);
const pathname = url.pathname;
const [owner, repo] = pathname.slice(1).split("/");
const apiURL = `https://api.github.com/repos/${owner}/${repo}`;
const response = await fetch(apiURL);

try {
if (!response.ok) {
const errorData = await response.json();
console.error(`Error fetching data from GitHub API: ${response.status} ${response.statusText}`);
console.error("Error details:", errorData);
return;
}

const data = await response.json();
return data.stargazers_count;
} catch (error) {
console.error("Error fetching GitHub stars:", error);
}
}
}

GitHubStars();
10 changes: 6 additions & 4 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@
</style>
<link rel="stylesheet" href="/assets/css/style.css" />

<script defer type="module" src="/assets/js/script-stars.js"></script>

<!-- Umami - Privacy preserving analytics tracking script -->
<script
defer
Expand Down Expand Up @@ -179,9 +181,9 @@ <h2 id="projects">
</h2>

<ul>
<li role="article">
<li role="article" class="github-project">
<header>
<h3 id="project-omnivore-epub">
<h3 id="project-omnivore-epub" data-url="https://github.com/agrmohit/omnivore-epub">
omnivore epub<a
href="#project-omnivore-epub"
class="anchor-link"
Expand All @@ -206,9 +208,9 @@ <h3 id="project-omnivore-epub">
</header>
</li>

<li role="article">
<li role="article" class="github-project">
<header>
<h3 id="project-userscripts">
<h3 id="project-userscripts" data-url="https://github.com/agrmohit/userscripts">
userscripts<a
href="#project-userscripts"
class="anchor-link"
Expand Down

0 comments on commit 8a4a658

Please sign in to comment.