scratch-www/src/redux/session.js
2016-06-01 15:28:18 -04:00

72 lines
1.9 KiB
JavaScript

var keyMirror = require('keymirror');
var api = require('../mixins/api.jsx').api;
var tokenActions = require('./token.js');
var Types = keyMirror({
SET_SESSION: null,
SET_SESSION_ERROR: null
});
module.exports.Status = keyMirror({
FETCHED: null,
NOT_FETCHED: null,
FETCHING: null
});
module.exports.getInitialState = function (){
return {'status': module.exports.Status.NOT_FETCHED, 'results':{}};
};
module.exports.sessionReducer = function (state, action) {
// Reducer for handling changes to session state
if (typeof state === 'undefined') {
state = module.exports.getInitialState();
}
switch (action.type) {
case Types.SET_SESSION:
return action.session;
case Types.SET_SESSION_ERROR:
// TODO: do something with action.error
return state;
default:
return state;
}
};
module.exports.setSessionError = function (error) {
return {
type: Types.SET_SESSION_ERROR,
error: error
};
};
module.exports.setSession = function (status, results) {
return {
type: Types.SET_SESSION,
session: {'status': status,'results': results}
};
};
module.exports.refreshSession = function () {
return function (dispatch) {
dispatch(module.exports.setSession(module.exports.Status.NOT_FETCHED, {}));
api({
host: '',
uri: '/session/'
}, function (err, body) {
dispatch(module.exports.setSession(module.exports.Status.FETCHING, {}));
if (err) return dispatch(module.exports.setSessionError(err));
if (typeof body !== 'undefined') {
if (body.banned) {
return window.location = body.url;
} else {
dispatch(tokenActions.getToken());
dispatch(module.exports.setSession(module.exports.Status.FETCHED, body));
return;
}
}
});
};
};