2016-10-16 12:37:37 +13:00
|
|
|
|
|
|
|
|
import actions from './actions'
|
|
|
|
|
|
|
|
|
|
const SpotifyMiddleware = (function(){
|
|
|
|
|
|
2016-10-17 10:39:11 +13:00
|
|
|
/**
|
|
|
|
|
* 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 = {
|
2016-10-17 10:39:11 +13:00
|
|
|
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-17 10:39:11 +13:00
|
|
|
}
|
2016-10-16 13:28:21 +13:00
|
|
|
|
2016-10-17 10:39:11 +13:00
|
|
|
/**
|
|
|
|
|
* The actual middleware inteceptor
|
|
|
|
|
**/
|
|
|
|
|
return store => next => action => {
|
2016-10-16 12:37:37 +13:00
|
|
|
|
2016-10-18 21:57:29 +13:00
|
|
|
var state = store.getState();
|
|
|
|
|
|
|
|
|
|
switch(action.type){
|
2016-10-17 10:39:11 +13:00
|
|
|
|
2016-10-19 14:09:34 +13:00
|
|
|
case 'SPOTIFY_AUTHORIZATION_GRANTED':
|
|
|
|
|
sendRequest( action.data.access_token, 'me' )
|
|
|
|
|
.then( (response) => {
|
|
|
|
|
var data = action.data;
|
|
|
|
|
data.me = response;
|
|
|
|
|
store.dispatch({ type: 'SPOTIFY_AUTHORIZATION_COMPLETE', data: data })
|
|
|
|
|
});
|
|
|
|
|
break;
|
|
|
|
|
|
2016-10-16 12:37:37 +13:00
|
|
|
// This action is irrelevant to us, pass it on to the next middleware
|
|
|
|
|
default:
|
|
|
|
|
return next(action);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
})();
|
|
|
|
|
|
|
|
|
|
export default SpotifyMiddleware
|