mattermost-mobile/service/actions/helpers.js
enahum d2f2678880 Reauthenticate from stored token when app is reloaded (#137)
* Reauthenticate from stored token when app is reloaded

* Address feedback
2016-12-15 13:17:26 -05:00

65 lines
1.7 KiB
JavaScript

// Copyright (c) 2016 Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.
import Client from 'service/client';
import {UsersTypes} from 'service/constants';
const HTTP_UNAUTHORIZED = 401;
export async function forceLogoutIfNecessary(err, dispatch) {
if (err.status_code === HTTP_UNAUTHORIZED && err.url.indexOf('/login') === -1) {
dispatch({type: UsersTypes.LOGOUT_REQUEST});
await Client.logout();
dispatch({type: UsersTypes.LOGOUT_SUCCESS});
}
}
function dispatcher(type, data, dispatch, getState) {
if (type.indexOf('SUCCESS') === -1) { // we don't want to pass the data for the request types
dispatch(requestSuccess(type, data), getState);
} else {
dispatch(requestData(type), getState);
}
}
export function requestData(type) {
return {
type
};
}
export function requestSuccess(type, data) {
return {
type,
data
};
}
export function requestFailure(type, error) {
return {
type,
error
};
}
export function bindClientFunc(clientFunc, request, success, failure, ...args) {
return async (dispatch, getState) => {
dispatch(requestData(request), getState);
let data = null;
try {
data = await clientFunc(...args);
} catch (err) {
forceLogoutIfNecessary(err, dispatch);
dispatch(requestFailure(failure, err), getState);
return;
}
if (Array.isArray(success)) {
success.forEach((s) => {
dispatcher(s, data, dispatch, getState);
});
} else {
dispatcher(success, data, dispatch, getState);
}
};
}