|
| 1 | +/// <reference types="@cloudflare/workers-types" /> |
| 2 | + |
| 3 | +// functions/api/extensions.ts |
| 4 | + |
| 5 | +import { getOctokit, type GitHubAppEnv } from './github-auth'; |
| 6 | + |
| 7 | +const CACHE_DURATION = 60 * 60; // Cache duration in seconds |
| 8 | + |
| 9 | +interface ExtensionRepository { |
| 10 | + name: string; |
| 11 | + owner: string; |
| 12 | + description: string | null; |
| 13 | + stars: number; |
| 14 | + url: string; |
| 15 | +} |
| 16 | + |
| 17 | +interface CloudflarePagesFunctionEnv extends GitHubAppEnv { |
| 18 | + GITHUB_CACHE: KVNamespace; |
| 19 | +} |
| 20 | + |
| 21 | +interface CloudflarePagesFunctionContext { |
| 22 | + env: CloudflarePagesFunctionEnv; |
| 23 | +} |
| 24 | + |
| 25 | +export async function onRequest( |
| 26 | + context: CloudflarePagesFunctionContext |
| 27 | +): Promise<Response> { |
| 28 | + const cacheKey = 'gate-extension-repositories'; |
| 29 | + |
| 30 | + // Access the KV namespace from context.env |
| 31 | + const GITHUB_CACHE = context.env.GITHUB_CACHE; |
| 32 | + |
| 33 | + // Check for cached data |
| 34 | + const cachedResponse = await GITHUB_CACHE.get(cacheKey); |
| 35 | + if (cachedResponse) { |
| 36 | + return new Response(cachedResponse, { |
| 37 | + headers: { |
| 38 | + 'Content-Type': 'application/json', |
| 39 | + 'Access-Control-Allow-Origin': '*', |
| 40 | + }, |
| 41 | + }); |
| 42 | + } |
| 43 | + |
| 44 | + try { |
| 45 | + // Get authenticated Octokit instance |
| 46 | + const octokit = await getOctokit(context.env, GITHUB_CACHE); |
| 47 | + |
| 48 | + // Search for repositories with topic:gate-extension |
| 49 | + const { data } = await octokit.request('GET /search/repositories', { |
| 50 | + q: 'topic:gate-extension', |
| 51 | + sort: 'stars', |
| 52 | + order: 'desc', |
| 53 | + }); |
| 54 | + |
| 55 | + const libraries: ExtensionRepository[] = data.items.map((item) => ({ |
| 56 | + name: item.name, |
| 57 | + owner: item.owner?.login ?? 'unknown', |
| 58 | + description: item.description, |
| 59 | + stars: item.stargazers_count, |
| 60 | + url: item.html_url, |
| 61 | + })); |
| 62 | + |
| 63 | + // Cache the response |
| 64 | + await GITHUB_CACHE.put(cacheKey, JSON.stringify(libraries), { |
| 65 | + expirationTtl: CACHE_DURATION, |
| 66 | + }); |
| 67 | + |
| 68 | + return new Response(JSON.stringify(libraries), { |
| 69 | + headers: { |
| 70 | + 'Content-Type': 'application/json', |
| 71 | + 'Access-Control-Allow-Origin': '*', |
| 72 | + 'Access-Control-Allow-Methods': 'GET', |
| 73 | + 'Access-Control-Allow-Headers': 'Content-Type', |
| 74 | + }, |
| 75 | + }); |
| 76 | + } catch (error) { |
| 77 | + const errorMessage = |
| 78 | + error instanceof Error ? error.message : 'Unknown error'; |
| 79 | + return new Response(`Error fetching data: ${errorMessage}`, { |
| 80 | + status: 500, |
| 81 | + }); |
| 82 | + } |
| 83 | +} |
| 84 | + |
0 commit comments