your personal website on atproto - mirror blento.app

add npmx-leaderboard api

+44
+44
src/routes/api/npmx-leaderboard/+server.ts
··· 1 + import { json } from '@sveltejs/kit'; 2 + import type { RequestHandler } from './$types'; 3 + 4 + const LEADERBOARD_API_URL = 5 + 'https://npmx-likes-leaderboard-api-production.up.railway.app/api/leaderboard/likes'; 6 + 7 + export const GET: RequestHandler = async ({ platform }) => { 8 + const cacheKey = '#npmx-leaderboard:likes'; 9 + const cachedData = await platform?.env?.USER_DATA_CACHE?.get(cacheKey); 10 + 11 + if (cachedData) { 12 + const parsedCache = JSON.parse(cachedData); 13 + 14 + const TWELVE_HOURS = 12 * 60 * 60 * 1000; 15 + const now = Date.now(); 16 + 17 + if (now - (parsedCache.updatedAt || 0) < TWELVE_HOURS) { 18 + return json(parsedCache.data); 19 + } 20 + } 21 + 22 + try { 23 + const response = await fetch(LEADERBOARD_API_URL); 24 + 25 + if (!response.ok) { 26 + return json( 27 + { error: 'Failed to fetch npmx leaderboard ' + response.statusText }, 28 + { status: response.status } 29 + ); 30 + } 31 + 32 + const data = await response.json(); 33 + 34 + await platform?.env?.USER_DATA_CACHE?.put( 35 + cacheKey, 36 + JSON.stringify({ data, updatedAt: Date.now() }) 37 + ); 38 + 39 + return json(data); 40 + } catch (error) { 41 + console.error('Error fetching npmx leaderboard:', error); 42 + return json({ error: 'Failed to fetch npmx leaderboard' }, { status: 500 }); 43 + } 44 + };