your personal website on atproto - mirror
blento.app
1import { json } from '@sveltejs/kit';
2import type { RequestHandler } from './$types';
3import type { GitHubContributionsData } from '$lib/cards/GitHubProfileCard/types';
4
5const GithubAPIURL = 'https://edge-function-github-contribution.vercel.app/api/github-data?user=';
6
7export const GET: RequestHandler = async ({ url, platform }) => {
8 const user = url.searchParams.get('user');
9
10 if (!user) {
11 return json({ error: 'No user provided' }, { status: 400 });
12 }
13
14 const cachedData = await platform?.env?.USER_DATA_CACHE?.get('#github:' + user);
15
16 if (cachedData) {
17 const parsedCache = JSON.parse(cachedData);
18
19 const TWELVE_HOURS = 12 * 60 * 60 * 1000;
20 const now = Date.now();
21
22 if (now - (parsedCache.updatedAt || 0) < TWELVE_HOURS) {
23 return json(parsedCache);
24 }
25 }
26
27 try {
28 const response = await fetch(GithubAPIURL + user);
29 console.log('hello', user);
30
31 if (!response.ok) {
32 console.log('error', response.statusText);
33 return json(
34 { error: 'Failed to fetch GitHub data ' + response.statusText },
35 { status: response.status }
36 );
37 }
38
39 const data = await response.json();
40
41 if (!data?.user) {
42 console.log('user not found', response.statusText);
43 return json({ error: 'User not found' }, { status: 404 });
44 }
45
46 const result = data.user as GitHubContributionsData;
47 result.updatedAt = Date.now();
48
49 await platform?.env?.USER_DATA_CACHE?.put('#github:' + user, JSON.stringify(result));
50
51 return json(result);
52 } catch (error) {
53 console.error('Error fetching GitHub contributions:', error);
54 return json({ error: 'Failed to fetch GitHub data' }, { status: 500 });
55 }
56};