Skip to content

Commit

Permalink
Add now playing and top tracks
Browse files Browse the repository at this point in the history
  • Loading branch information
mareksuscak committed Nov 20, 2021
1 parent 0afd35d commit 376cc3a
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
40 changes: 40 additions & 0 deletions pages/api/now-playing.ts
@@ -0,0 +1,40 @@
import type { NextApiRequest, NextApiResponse } from 'next';
import { getNowPlaying } from 'lib/spotify';

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
});
}
23 changes: 23 additions & 0 deletions pages/api/top-tracks.ts
@@ -0,0 +1,23 @@
import type { NextApiRequest, NextApiResponse } from 'next';
import { getTopTracks } from 'lib/spotify';

export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const response = await getTopTracks();
const { items } = await response.json();

const tracks = items.slice(0, 10).map((track) => ({
artist: track.artists.map((_artist: any) => _artist.name).join(', '),
songUrl: track.external_urls.spotify,
title: track.name
}));

res.setHeader(
'Cache-Control',
'public, s-maxage=86400, stale-while-revalidate=43200'
);

return res.status(200).json({ tracks });
}

0 comments on commit 376cc3a

Please sign in to comment.