Pusher part one

This commit is contained in:
James Barnsley
2016-10-27 16:58:11 +13:00
parent c4fcf43b3c
commit 6de44cda53
10 changed files with 192 additions and 10 deletions

View File

@ -0,0 +1,31 @@
/**
* Actions and Action Creators
**/
export function setConfig( config ){
return {
type: 'PUSHER_SET_CONFIG',
config: config
}
}
export function connect(){
return {
type: 'PUSHER_CONNECT'
}
}
export function disconnect(){
return {
type: 'PUSHER_DISCONNECT'
}
}
export function instruct( call, value ){
return {
type: 'PUSHER_INSTRUCT',
call: call,
value: value
}
}

View File

@ -0,0 +1,58 @@
var actions = require('./actions.js')
const PusherMiddleware = (function(){
// container for the actual Mopidy socket
var socket = null;
// handle all manner of socket messages
const handleMessage = (ws, store, message) => {
switch( message.action ){
default:
store.dispatch({ type: 'PUSHER_'+message.action.toUpperCase(), data: message.data })
}
}
/**
* Middleware
*
* This behaves like an action interceptor. We listen for specific actions
* and handle special functionality. If the action is not in our switch, then
* it just proceeds to the next middleware, or default functionality
**/
return store => next => action => {
switch(action.type) {
case 'PUSHER_CONNECT':
if(socket != null) socket.close();
store.dispatch({ type: 'PUSHER_CONNECTING' });
var state = store.getState();
socket = new WebSocket(
'ws://'+state.mopidy.host+':'+state.pusher.port+'/pusher'
);
socket.onopen = function(){
store.dispatch({ type: 'PUSHER_CONNECTED' });
};
socket.onmessage = function(message){
var message = JSON.parse(message.data);
handleMessage( socket, store, message )
};
break;
// This action is irrelevant to us, pass it on to the next middleware
default:
return next(action);
}
}
})();
export default PusherMiddleware

View File

@ -0,0 +1,23 @@
export default function reducer(pusher = {}, action){
switch (action.type) {
case 'PUSHER_CONNECTED':
return Object.assign({}, pusher, { connected: true, connecting: false });
case 'PUSHER_DISCONNECTED':
return Object.assign({}, pusher, { connected: false, connecting: false });
case 'PUSHER_SET_CONFIG':
return Object.assign({}, pusher, {
host: action.host,
port: action.port
});
default:
return pusher
}
}