Created
May 28, 2018 14:50
-
-
Save cdaz5/dd06c3044b60e79ef7312177bf31395f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| let accessToken = ''; | |
| const clientId = '664b972b62e44bec946cdda0e4d72ff9'; | |
| const redirectUri = 'http://localhost:3000/'; | |
| const Spotify = { | |
| getAccessToken() { | |
| if (accessToken) { | |
| return accessToken; | |
| console.log(`This is ${accessToken}`); | |
| } | |
| const accessTokenMatch = window.location.href.match(/access_token=([^&]*)/); | |
| const expiresInMatch = window.location.href.match(/expires_in=([^&]*)/); | |
| if (accessTokenMatch && expiresInMatch) { | |
| accessToken = accessTokenMatch[1]; | |
| const expiresIn = Number(expiresInMatch[1]); | |
| window.setTimeout(() => (accessToken = ''), expiresIn * 1000); | |
| window.history.pushState('Access Token', null, '/'); // This clears the parameters, allowing us to grab a new access token when it expires. | |
| return accessToken; | |
| } else { | |
| window.location = `https://accounts.spotify.com/authorize?client_id=${clientId}&response_type=token&scope=playlist-modify-public&redirect_uri=${redirectUri}`; | |
| } | |
| }, | |
| search(term) { | |
| const accessToken = Spotify.getAccessToken(); | |
| console.log('access', accessToken); | |
| return fetch(`https://api.spotify.com/v1/search?type=track&q=${term}`, { | |
| headers: { | |
| Authorization: `Bearer ${accessToken}` | |
| } | |
| }) | |
| .then(response => { | |
| return response.json(); | |
| }) | |
| .then(jsonResponse => { | |
| if (!jsonResponse.tracks) { | |
| return []; | |
| } | |
| console.log('response', jsonResponse); | |
| return jsonResponse.tracks.items.map(track => ({ | |
| id: track.id, | |
| name: track.name, | |
| artist: track.artists[0].name, | |
| album: track.album.name, | |
| URI: track.uri | |
| })); | |
| }); | |
| } | |
| }; | |
| export default Spotify; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment