(resources: { slug: string; stars?: number }[])
| 2 | const API_URL = "https://api.github.com/graphql"; |
| 3 | |
| 4 | export async function fetchStars(resources: { slug: string; stars?: number }[]) { |
| 5 | try { |
| 6 | if (resources.length === 0) return; |
| 7 | const uniqueSlugs = Array.from( |
| 8 | new Set( |
| 9 | resources |
| 10 | .filter((r) => r.stars === undefined) |
| 11 | .map((r, id) => ({ |
| 12 | id, |
| 13 | slug: r.slug, |
| 14 | })) |
| 15 | ) |
| 16 | ); |
| 17 | |
| 18 | if (uniqueSlugs.length === 0) return; |
| 19 | |
| 20 | const queryParts = uniqueSlugs.map(({ id, slug }) => { |
| 21 | const [owner, name] = slug.split("/"); |
| 22 | return ` |
| 23 | repo${id}: repository(owner: "${owner}", name: "${name}") { |
| 24 | stargazerCount |
| 25 | } |
| 26 | `; |
| 27 | }); |
| 28 | |
| 29 | const query = `{ ${queryParts.join("\n")} }`; |
| 30 | const res = await fetch(API_URL, { |
| 31 | method: "POST", |
| 32 | headers: { |
| 33 | Authorization: `Bearer ${GITHUB_TOKEN}`, |
| 34 | "Content-Type": "application/json", |
| 35 | }, |
| 36 | body: JSON.stringify({ query }), |
| 37 | next: { revalidate: 86400 }, // Cache for 1 day to match route revalidation |
| 38 | }); |
| 39 | |
| 40 | if (res.status > 400) { |
| 41 | console.error( |
| 42 | "Failed to fetch GitHub stars. Make sure you are providing a valid GITHUB_TOKEN in packages/docs/.env" |
| 43 | ); |
| 44 | if (process.env.NODE_ENV === "production") { |
| 45 | throw new Error("Failed to fetch GitHub stars."); |
| 46 | } |
| 47 | return; |
| 48 | } |
| 49 | |
| 50 | const json = await res.json(); |
| 51 | |
| 52 | if (json.errors) { |
| 53 | console.dir(json.errors, { depth: null }); |
| 54 | throw new Error("Failed to fetch GitHub stars"); |
| 55 | } |
| 56 | |
| 57 | // Create a map of slug → star count |
| 58 | const starsMap = new Map<string, number>(); |
| 59 | for (const slug of uniqueSlugs) { |
| 60 | const count = json.data[`repo${slug.id}`]?.stargazerCount; |
| 61 | if (typeof count === "number") { |
no test coverage detected