My personal site hosted @ https://indexx.dev
1import type { APIRoute } from "astro";
2const lastfmAPIKey = import.meta.env.LASTFM_API_KEY;
3
4if (!lastfmAPIKey) {
5 console.error(
6 "LASTFM_API_KEY is not defined. Please check your .env file.",
7 );
8}
9
10interface CacheItem {
11 data: any;
12 timestamp: number;
13}
14
15let cache: CacheItem | null = null;
16const CACHE_DURATION = 5 * 60 * 1000; // 5 minutes in milliseconds
17
18export const prerender = false;
19
20export const GET: APIRoute = async () => {
21 const now = Date.now();
22
23 if (cache && (now - cache.timestamp) < CACHE_DURATION) {
24 return Response.json(cache.data, {
25 status: 200,
26 headers: {
27 "X-Index-API-Cached": "true", // Debug
28 "Cache-Control": "max-age=300", // 5 minutes
29 },
30 });
31 }
32
33 try {
34 const apiRes = await fetch(
35 `http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=Index_Card&api_key=${lastfmAPIKey}&format=json`,
36 );
37
38 if (!apiRes.ok) {
39 return Response.json({}, {
40 status: 502,
41 });
42 }
43
44 const apiData: LastFmApiResponse = await apiRes.json();
45 const recentTrack = apiData.recenttracks.track[0];
46
47 const data = {
48 track: recentTrack.name,
49 artist: recentTrack.artist["#text"],
50 cover: recentTrack.image.find((img) =>
51 img.size == "medium"
52 )!["#text"],
53 url: recentTrack.url,
54 createdAt: recentTrack.date
55 ? new Date(parseInt(recentTrack.date.uts) * 1000).toISOString()
56 : null,
57 };
58
59 cache = {
60 data,
61 timestamp: Date.now(),
62 };
63
64 return Response.json(data, {
65 status: 200,
66 headers: {
67 "X-Index-API-Cached": "true", // Debug
68 "Cache-Control": "max-age=300", // 5 minutes
69 },
70 });
71 } catch (error) {
72 return Response.json({}, {
73 status: 500,
74 });
75 }
76};