Skip to content

Commit

Permalink
Updated now-playing API handler to use Edge runtime and return Respon…
Browse files Browse the repository at this point in the history
…se objects instead of using NextApiResponse
  • Loading branch information
lrmn7 committed Jun 27, 2024
1 parent 667ce06 commit d203135
Showing 1 changed file with 40 additions and 37 deletions.
77 changes: 40 additions & 37 deletions pages/api/now-playing.ts
Original file line number Diff line number Diff line change
@@ -1,41 +1,44 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { getNowPlaying } from "../../lib/spotify";

export const runtime = 'edge';
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const response = await getNowPlaying();

if (response.status === 204 || response.status > 400) {
return res.status(200).json({ isPlaying: false });
}

const song = await response.json();
if (song.item === null) {
return res.status(200).json({ isPlaying: false });
}
const isPlaying = song.is_playing;
const title = song.item.name;
const artist = song.item.artists
.map((_artist: any) => _artist.name)
.join(", ");
const album = song.item.album.name;
const albumImageUrl = song.item.album.images[0].url;
const songUrl = song.item.external_urls.spotify;

res.setHeader(
"Cache-Control",
"public, s-maxage=60, stale-while-revalidate=30"
);

return res.status(200).json({
album,
albumImageUrl,
artist,
isPlaying,
songUrl,
title,
});

export default async function handler(req: Request) {
const response = await getNowPlaying();

if (response.status === 204 || response.status > 400) {
return new Response(JSON.stringify({ isPlaying: false }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
}

const song = await response.json();
if (song.item === null) {
return new Response(JSON.stringify({ isPlaying: false }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
}

const isPlaying = song.is_playing;
const title = song.item.name;
const artist = song.item.artists.map((artist: any) => artist.name).join(", ");
const album = song.item.album.name;
const albumImageUrl = song.item.album.images[0].url;
const songUrl = song.item.external_urls.spotify;

const headers = new Headers({
"Cache-Control": "public, s-maxage=60, stale-while-revalidate=30",
"Content-Type": "application/json"
});

return new Response(JSON.stringify({
album,
albumImageUrl,
artist,
isPlaying,
songUrl,
title,
}), { headers });
}

0 comments on commit d203135

Please sign in to comment.