mirror of
https://github.com/yude-jp/yude.jp
synced 2024-12-22 12:10:11 +09:00
Add API route for Spotify
This commit is contained in:
parent
8ad79231a2
commit
019bf3c4ad
58
pages/api/Spotify.js
Normal file
58
pages/api/Spotify.js
Normal file
@ -0,0 +1,58 @@
|
||||
import querystring from 'querystring';
|
||||
|
||||
const {
|
||||
SPOTIFY_CLIENT_ID: client_id,
|
||||
SPOTIFY_CLIENT_SECRET: client_secret,
|
||||
SPOTIFY_REFRESH_TOKEN: refresh_token,
|
||||
} = process.env;
|
||||
|
||||
const basic = Buffer.from(`${client_id}:${client_secret}`).toString('base64');
|
||||
const NOW_PLAYING_ENDPOINT = `https://api.spotify.com/v1/me/player/currently-playing`;
|
||||
const TOKEN_ENDPOINT = `https://accounts.spotify.com/api/token`;
|
||||
|
||||
const getAccessToken = async () => {
|
||||
const response = await fetch(TOKEN_ENDPOINT, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Basic ${basic}`,
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
},
|
||||
body: querystring.stringify({
|
||||
grant_type: 'refresh_token',
|
||||
refresh_token,
|
||||
}),
|
||||
});
|
||||
|
||||
return response.json();
|
||||
};
|
||||
|
||||
export const getNowPlaying = async () => {
|
||||
const { access_token } = await getAccessToken();
|
||||
|
||||
return fetch(NOW_PLAYING_ENDPOINT, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${access_token}`,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
export default async (_, res) => {
|
||||
const response = await getNowPlaying();
|
||||
|
||||
if (response.status === 204 || response.status > 400) {
|
||||
return res.status(200).json({ isPlaying: false });
|
||||
}
|
||||
|
||||
const song = await response.json();
|
||||
const isPlaying = song.is_playing;
|
||||
const title = song.item.name;
|
||||
const artist = song.item.artists.map((_artist) => _artist.name).join(', ');
|
||||
const album = song.item.album.name;
|
||||
|
||||
return res.status(200).json({
|
||||
album,
|
||||
artist,
|
||||
isPlaying,
|
||||
title,
|
||||
});
|
||||
};
|
Loading…
Reference in New Issue
Block a user