Commit 38617bac authored by Oleksii Savran's avatar Oleksii Savran Committed by Matija Obreza

SSR iso3166 decodings

parent 288b507a
export default function fetchComponentData(dispatch, branch, search, state = null) {
const promisesWithProps = [];
const promisesWithProps = [];
branch.map(({ route, match }) => {
const component = route.component;
branch.map(({ route, match }) => {
const component = route.component;
if (!component || !component.needs && (!component.WrappedComponent || !component.WrappedComponent.needs)) {
return;
}
if (!component || !component.needs && (!component.WrappedComponent || !component.WrappedComponent.needs)) {
return;
}
const ownProps = { route, match };
// console.log('SSR need with arguments (state, ownProps, search)=', '..snip..'); // , ownProps, search);
const ownProps = { route, match };
// console.log('SSR need with arguments (state, ownProps, search)=', '..snip..'); // , ownProps, search);
const needs = component.needs || component.WrappedComponent && component.WrappedComponent.needs;
// Provide params to static needs
needs && needs.filter((need) => need({ state, ownProps, search, params: match.params })).map((need) => {
return dispatch(need({ state, ownProps, search, params: match.params }));
})
// a nice array of Promises
.forEach((promise) => promisesWithProps.push(promise));
});
const needs = component.needs || component.WrappedComponent && component.WrappedComponent.needs;
// Provide params to static needs
needs && needs.filter((need) => need({ state, ownProps, search, params: match.params })).map((need) => {
return dispatch(need({ state, ownProps, search, params: match.params }));
})
// a nice array of Promises
.forEach((promise) => promisesWithProps.push(promise));
});
return Promise.all(promisesWithProps);
return Promise.all(promisesWithProps);
}
......@@ -59,15 +59,15 @@ const prerenderer = (html, errHtml) => (req, res) => {
return res.status(503).set('Content-Type', 'text/html').send(errFilledHtml);
}
initFromServerStorage(serverStorage, store.dispatch);
// console.log(`Processing request`, req._parsedOriginalUrl);
const pathname = req._parsedOriginalUrl.pathname;
const search = req._parsedOriginalUrl.search;
const context = {};
const locale = detectLocaleFromPath(config.frontendPath, pathname, 0);
initFromServerStorage(serverStorage, store.dispatch, locale);
function setLocale() {
const locale = detectLocaleFromPath(config.frontendPath, pathname, 0);
function setLocale(locale) {
// console.log('Detected locale for SSR is', locale);
req.i18n.changeLanguage(locale);
import(`javascript-time-ago/locale/${locale}`).then((timeAgoLocale) => TimeAgo.locale(timeAgoLocale));
......@@ -166,7 +166,7 @@ const prerenderer = (html, errHtml) => (req, res) => {
});
}
setLocale();
setLocale(locale);
checkAuthToken(req, res, store.dispatch).then(() => {
const language = req.i18n.language;
......
......@@ -2,11 +2,14 @@
import 'babel-polyfill';
import { RECEIVE_CROPS } from 'crop/constants';
import { GET_SERVER_INFO } from 'constants/serverInfo';
import { RECEIVE_COUNTRY_CODES_DECODED } from 'geo/constants';
import languages from 'data/Languages';
// model
import ApiCall from 'model/ApiCall';
// service
import { CropService } from 'service/CropService';
import ApiInfoService from 'service/genesys/ApiInfoService';
import VocabularyService from 'service/catalog/VocabularyService';
// server
import config from '../config';
......@@ -24,6 +27,11 @@ export const serverStorage = {
data: null,
loaded: false,
},
countryCodes: {
actionType: RECEIVE_COUNTRY_CODES_DECODED,
data: {},
loaded: false,
},
};
const directXhrConfig = {
......@@ -62,9 +70,26 @@ const refreshServerInfo = (): Promise<boolean> => {
});
};
export const refreshCountryCodes = async (): Promise<boolean> => {
const start = Date.now();
try {
for (const lang of languages) {
const codes = await VocabularyService.decode3166Alpha3Terms(lang.short);
serverStorage.countryCodes.data[lang.short] = {apiCall: ApiCall.success(codes)};
}
console.log(`CountryCodes fetched in ${Date.now() - start}ms`);
serverStorage.countryCodes.loaded = true;
return true;
} catch (e) {
console.log(`refreshCountryCodes failed`, e);
return false;
}
};
export const refreshServerStorage = async () => {
await refreshServerInfo();
await refreshCrops();
await refreshCountryCodes();
const storageLoaded = isServerStorageLoaded();
const timeout = storageLoaded ? REFRESH_TIME : 1000 + 5000 * Math.random();
console.log(`Server storage refresh executed ${storageLoaded}. Refresh in ${timeout}ms`);
......
export const initFromServerStorage = (serverStorage, dispatch, lang: string) => {
export const initFromServerStorage = (serverStorage, dispatch) => {
// console.log('ServerStorage: ', serverStorage);
Object.keys(serverStorage).forEach((key) => dispatch({type: serverStorage[key].actionType, payload: serverStorage[key].data }));
Object.keys(serverStorage).forEach((key) => {
if (key === 'countryCodes') {
// set countryCodes according to lang
if (serverStorage[key].data[lang]) {
// console.log(`countryCodes for ${lang}'`);
return dispatch({type: serverStorage[key].actionType, payload: serverStorage[key].data[lang] });
}
} else {
return dispatch({type: serverStorage[key].actionType, payload: serverStorage[key].data });
}
});
};
......@@ -38,3 +38,22 @@ export const getCountry = (code) => (dispatch) => {
export const loadIso3Decodings = (lang) => (dispatch) => {
return dispatch(apiDecode3166Alpha3Terms(lang));
};
export const refreshIso3Decodings = (lang: string) => (dispatch, getState) => {
const countryCodes = getState().decoder.countryCodes;
const TIMEOUT_MINUTES = 5;
if (countryCodes && countryCodes.timestamp) {
const timeout = TIMEOUT_MINUTES * 60 * 1000 - (Date.now() - countryCodes.timestamp);
console.log(`refreshIso3Decodings in ${timeout / 1000}s`);
setTimeout(() => {
dispatch(apiDecode3166Alpha3Terms(lang))
.then(() => dispatch(refreshIso3Decodings(lang)))
.catch((e) => console.log('refreshIso3Decodings failed', e));
}, timeout);
} else {
dispatch(apiDecode3166Alpha3Terms(lang))
.then(() => dispatch(refreshIso3Decodings(lang)))
.catch((e) => console.log('load Iso3Decodings failed', e));
}
};
......@@ -9,7 +9,7 @@ import { loadCrops } from 'crop/actions/public';
import { initMyList } from 'list/actions/public';
import { initMyMaps } from 'accessions/actions/public';
import { checkSoftwareVersion, serverInfoRequest } from 'actions/serverInfo';
import { loadIso3Decodings } from 'geo/actions/public';
import { loadIso3Decodings, refreshIso3Decodings } from 'geo/actions/public';
import { withRouter } from 'react-router-dom';
......@@ -22,6 +22,7 @@ import Crop from 'model/genesys/Crop';
import ApiCall from 'model/ApiCall';
import ActivityPost from 'model/cms/ActivityPost';
interface IAppProps extends React.ClassAttributes<any>, WithTranslation {
children: any;
login: any;
......@@ -38,20 +39,18 @@ interface IAppProps extends React.ClassAttributes<any>, WithTranslation {
checkSoftwareVersion: any;
initMyMaps: any;
currentPost: ApiCall<ActivityPost>;
refreshIso3Decodings: (lang: string) => void;
lang: string;
}
class App extends React.Component<IAppProps, any> {
public static needs = [
({ state }) => loadIso3Decodings(state.applicationConfig.lang),
];
public constructor(props: any) {
super(props);
}
public componentDidMount() {
const { initMyList, checkSoftwareVersion , initMyMaps } = this.props;
const { initMyList, checkSoftwareVersion , initMyMaps, refreshIso3Decodings, lang } = this.props;
const { crops, loadCrops, serverInfo, serverInfoRequest} = this.props;
if (! crops || crops.length === 0) {
loadCrops();
......@@ -63,6 +62,7 @@ class App extends React.Component<IAppProps, any> {
initMyList();
initMyMaps();
refreshIso3Decodings(lang);
console.log('Loading software version');
checkSoftwareVersion();
}
......@@ -127,7 +127,7 @@ const mapStateToProps = (state) => ({
countryCodes: state.decoder.countryCodes,
crops: state.crop.public.list ? state.crop.public.list.data : undefined,
serverInfo: state.serverInfo.data,
lang: state.applicationConfig.lang.data,
lang: state.applicationConfig.lang,
currentPost: state.cms.public.activityPost.currentPost,
});
......@@ -139,6 +139,7 @@ const mapDispatchToProps = (dispatch) => bindActionCreators({
checkSoftwareVersion,
loadIso3Decodings,
initMyMaps,
refreshIso3Decodings,
}, dispatch);
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(withTranslation()(App)));
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment