Files
Iris/src/js/services/spotify/middleware.js

96 lines
2.9 KiB
JavaScript
Raw Normal View History

import actions from './actions'
const SpotifyMiddleware = (function(){
/**
* Send an ajax request to the Spotify API
*
* @param endpoint string = the url to query (ie /albums/:uri)
* @param method string
* @param data mixed = request payload
* @return ajax promise
**/
2016-10-17 14:27:48 +13:00
const sendRequest = (token, endpoint, method = 'GET', data = false) => {
var options = {
method: method,
cache: true,
url: 'https://api.spotify.com/v1/'+endpoint,
data: data
2016-10-17 14:27:48 +13:00
};
if( token ){
options.headers = {
Authorization: 'Bearer '+ token
}
}
return $.ajax( options );
}
2016-10-16 13:28:21 +13:00
/**
* The actual middleware inteceptor
**/
return store => next => action => {
switch(action.type) {
2016-10-16 13:28:21 +13:00
case 'SPOTIFY_LOAD_ALBUM':
store.dispatch({ type: 'SPOTIFY_ALBUM_LOADED', data: false })
var id = action.uri.replace('spotify:album:','');
2016-10-17 14:27:48 +13:00
sendRequest( false, 'albums/'+id )
.then( (response) => {
store.dispatch({ type: 'SPOTIFY_ALBUM_LOADED', data: response })
});
2016-10-16 13:28:21 +13:00
break;
case 'SPOTIFY_LOAD_ARTIST':
store.dispatch({ type: 'SPOTIFY_ARTIST_LOADED', data: false })
var id = action.uri.replace('spotify:artist:','');
2016-10-17 14:27:48 +13:00
sendRequest( false, 'artists/'+id )
.then( (response) => {
store.dispatch({ type: 'SPOTIFY_ARTIST_LOADED', data: response })
});
break;
2016-10-17 14:27:48 +13:00
case 'SPOTIFY_LOAD_LIBRARY_ARTISTS':
store.dispatch({ type: 'SPOTIFY_LIBRARY_ARTISTS_LOADED', data: false })
var token = store.getState().spotify.token;
sendRequest( token, 'me/following?type=artist' )
.then( (response) => {
store.dispatch({ type: 'SPOTIFY_LIBRARY_ARTISTS_LOADED', data: response })
});
break;
case 'SPOTIFY_CONNECT':
console.log('Spotify wants to connect')
break;
case 'SPOTIFY_DISCONNECT':
console.log('Spotify wants to DISconnect')
break;
2016-10-18 08:56:53 +13:00
case 'SPOTIFY_COMPLETE_AUTHORIZATION':
next(action);
localStorage.setItem('spotify', JSON.stringify({ access_token: action.data.access_token, refresh_token: action.data.refresh_token }));
break;
// This action is irrelevant to us, pass it on to the next middleware
default:
return next(action);
}
}
})();
export default SpotifyMiddleware