Dynamic realtime profile ReadMe linked with spotify
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

46 lines
1.2 KiB

  1. import fetch from "isomorphic-unfetch";
  2. import { stringify } from "querystring";
  3. const {
  4. SPOTIFY_CLIENT_ID: client_id,
  5. SPOTIFY_CLIENT_SECRET: client_secret,
  6. SPOTIFY_REFRESH_TOKEN: refresh_token,
  7. } = process.env;
  8. const basic = Buffer.from(`${client_id}:${client_secret}`).toString("base64");
  9. const Authorization = `Basic ${basic}`;
  10. async function getAuthorizationToken() {
  11. const url = new URL("https://accounts.spotify.com/api/token");
  12. const body = stringify({
  13. grant_type: "refresh_token",
  14. refresh_token,
  15. });
  16. const response = await fetch(`${url}`, {
  17. method: "POST",
  18. headers: {
  19. Authorization,
  20. "Content-Type": "application/x-www-form-urlencoded",
  21. },
  22. body,
  23. }).then((r) => r.json());
  24. return `Bearer ${response.access_token}`;
  25. }
  26. const NOW_PLAYING_ENDPOINT = `https://api.spotify.com/v1/me/player/currently-playing`;
  27. export async function nowPlaying() {
  28. const Authorization = await getAuthorizationToken();
  29. const response = await fetch(NOW_PLAYING_ENDPOINT, {
  30. headers: {
  31. Authorization,
  32. },
  33. });
  34. const { status } = response;
  35. if (status === 204) {
  36. return {};
  37. } else if (status === 200) {
  38. const data = await response.json();
  39. return data;
  40. }
  41. }