Skip to content

Commit

Permalink
fetch star count from repo
Browse files Browse the repository at this point in the history
  • Loading branch information
ahmedkhaleel2004 committed Dec 25, 2024
1 parent 4f1aefb commit ab5a15f
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 3 deletions.
31 changes: 31 additions & 0 deletions src/app/_actions/github.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { cache } from "react";

interface GitHubResponse {
stargazers_count: number;
}

export const getStarCount = cache(async () => {
try {
const response = await fetch(
"https://api.github.com/repos/ahmedkhaleel2004/gitdiagram",
{
headers: {
Accept: "application/vnd.github.v3+json",
},
next: {
revalidate: 300, // Cache for 5 minutes
},
},
);

if (!response.ok) {
throw new Error("Failed to fetch star count");
}

const data = (await response.json()) as GitHubResponse;
return data.stargazers_count;
} catch (error) {
console.error("Error fetching star count:", error);
return null;
}
});
2 changes: 1 addition & 1 deletion src/app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import Hero from "~/components/hero";
export default function HomePage() {
return (
<main className="flex-grow p-8">
<div className="mx-auto my-4 max-w-4xl lg:my-12">
<div className="mx-auto my-4 max-w-4xl lg:my-8">
<Hero />
<div className="mt-12"></div>
<p className="mx-auto mt-8 max-w-2xl text-center text-lg">
Expand Down
15 changes: 13 additions & 2 deletions src/components/header.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,19 @@
import React from "react";
import Link from "next/link";
import { FaGithub } from "react-icons/fa";
import { getStarCount } from "~/app/_actions/github";

export async function Header() {
const starCount = await getStarCount();

const formatStarCount = (count: number | null) => {
if (!count) return "0";
if (count >= 1000) {
return `${(count / 1000).toFixed(1)}k`;
}
return count.toString();
};

export function Header() {
return (
<header className="border-b-[3px] border-black">
<div className="mx-auto flex h-16 max-w-4xl items-center justify-between px-8">
Expand Down Expand Up @@ -32,7 +43,7 @@ export function Header() {
</Link>
<span className="flex items-center gap-1 text-sm font-medium text-black">
<span className="text-amber-400"></span>
1.3k
{formatStarCount(starCount)}
</span>
</nav>
</div>
Expand Down

0 comments on commit ab5a15f

Please sign in to comment.