accounts-frontend/src/components/user/factory.ts

51 lines
1.4 KiB
TypeScript
Raw Normal View History

import { authenticate, logoutStrangers } from 'components/accounts/actions';
import { getActiveAccount } from 'components/accounts/reducer';
import request from 'services/request';
2019-12-07 16:58:52 +05:30
import { Store } from 'reducers';
import { changeLang } from './actions';
import bearerHeaderMiddleware from './middlewares/bearerHeaderMiddleware';
import refreshTokenMiddleware from './middlewares/refreshTokenMiddleware';
2019-12-07 16:58:52 +05:30
let promise: Promise<void>;
2016-08-10 00:47:49 +05:30
/**
* Initializes User state with the fresh data
*
* @param {object} store - redux store
*
* @returns {Promise<User>} - a promise, that resolves in User state
*/
2019-12-07 16:58:52 +05:30
export function factory(store: Store): Promise<void> {
if (promise) {
return promise;
}
2016-08-10 00:47:49 +05:30
request.addMiddleware(refreshTokenMiddleware(store));
request.addMiddleware(bearerHeaderMiddleware(store));
promise = Promise.resolve()
.then(() => store.dispatch(logoutStrangers()))
2019-12-07 16:58:52 +05:30
.then(async () => {
const activeAccount = getActiveAccount(store.getState());
if (activeAccount) {
// authorizing user if it is possible
2019-12-07 16:58:52 +05:30
await store.dispatch(authenticate(activeAccount));
return;
}
return Promise.reject();
})
2019-12-07 16:58:52 +05:30
.catch(async () => {
// the user is guest or user authentication failed
const { user } = store.getState();
// auto-detect guest language
2019-12-07 16:58:52 +05:30
await store.dispatch(changeLang(user.lang));
});
2016-08-10 00:47:49 +05:30
return promise;
}