Skip to content

Commit

Permalink
ADD History service
Browse files Browse the repository at this point in the history
  • Loading branch information
ahmetkuslular committed Mar 2, 2022
1 parent 6482ec9 commit e33858d
Show file tree
Hide file tree
Showing 7 changed files with 102 additions and 9 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@
"file-loader": "1.1.11",
"helmet": "3.21.3",
"hiddie": "^1.0.0",
"history": "^5.3.0",
"husky": "^3.1.0",
"identity-obj-proxy": "3.0.0",
"intersection-observer": "0.7.0",
Expand Down
20 changes: 18 additions & 2 deletions src/render.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,27 @@ import logger from './universal/utils/logger';
import omit from 'lodash/omit';

const appConfig = require('__APP_CONFIG__');
const previewPages = require('__V_PREVIEW_PAGES__');

function getPreview(output) {
const { layouts = {} } = previewPages?.default || {};
let PreviewFile = Preview;

console.log('layouts:', layouts);
if (layouts.default) {
PreviewFile = layouts.default;
}

return PreviewFile(output);
}

const render = async (req, res) => {
const isWithoutStateValue = isWithoutState(req.query);
const pathParts = xss(req.path)
.split('/')
.filter(part => part);
const componentPath = `/${pathParts.join('/')}`;
const isPreviewValue = isPreview(req.query);

const routeInfo = matchUrlInRouteConfigs(componentPath);

Expand All @@ -38,7 +52,8 @@ const render = async (req, res) => {
.replace('//', '/'),
userAgent: Buffer.from(req.headers['user-agent'] || [], 'utf-8').toString('base64'),
headers: JSON.parse(xss(JSON.stringify(req.headers))),
isWithoutState: isWithoutStateValue
isWithoutState: isWithoutStateValue,
isPreview: isPreviewValue
};

const component = new Component(routeInfo.path);
Expand Down Expand Up @@ -82,7 +97,8 @@ const render = async (req, res) => {
const voltranEnv = appConfig.voltranEnv || 'local';

if (voltranEnv !== 'prod' && isPreviewQuery) {
res.status(statusCode).html(Preview([fullHtml].join('\n')));
const response = getPreview([fullHtml].join('\n'));
res.status(statusCode).html(response);
} else {
res
.status(HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR)
Expand Down
10 changes: 7 additions & 3 deletions src/renderMultiple.js
Original file line number Diff line number Diff line change
Expand Up @@ -145,9 +145,13 @@ async function setInitialStates(renderers) {
winner
.execute()
.then(response => callback(null, response))
.catch(exception =>
callback(new Error(`${winner.uri} : ${exception.message}`), null)
);
.catch(exception => {
if (renderer.component.object.byPassWhenFailed) {
callback(null, { data: { isFailed: true } });
} else {
callback(new Error(`${winner.uri} : ${exception.message}`), null);
}
});
};
}
});
Expand Down
2 changes: 1 addition & 1 deletion src/universal/partials/Welcome/partials.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ Object.keys(components).forEach(path => {
partials.push({
name: info.fragmentName,
url: path,
status: info.status
status: info?.fragment?.previewStatus || info.status
});
}
});
Expand Down
14 changes: 12 additions & 2 deletions src/universal/partials/withBaseComponent.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import ClientApp from '../components/ClientApp';
import { WINDOW_GLOBAL_PARAMS } from '../utils/constants';
import { createComponentName } from '../utils/helper';
import voltranConfig from '../../../voltran.config';
import HistoryService from '../service/HistoryService';

const getStaticProps = () => {
const staticProps = {};
Expand All @@ -24,7 +25,12 @@ const withBaseComponent = (PageComponent, pathName) => {

if (process.env.BROWSER && window[prefix] && window[prefix][componentName.toUpperCase()]) {
const fragments = window[prefix][componentName.toUpperCase()];
const history = window[WINDOW_GLOBAL_PARAMS.HISTORY];

window[WINDOW_GLOBAL_PARAMS.VOLTRAN_HISTORY] =
window[WINDOW_GLOBAL_PARAMS.VOLTRAN_HISTORY] ||
new HistoryService(WINDOW_GLOBAL_PARAMS.VOLTRAN_HISTORY);
const history = window[WINDOW_GLOBAL_PARAMS.VOLTRAN_HISTORY].getHistory();

const staticProps = getStaticProps();

Object.keys(fragments).forEach(id => {
Expand All @@ -37,7 +43,11 @@ const withBaseComponent = (PageComponent, pathName) => {

ReactDOM.hydrate(
<ClientApp>
<PageComponent {...staticProps} initialState={initialState} history={history} />
<PageComponent
{...staticProps}
initialState={initialState}
history={history}
/>
</ClientApp>,
componentEl,
() => {
Expand Down
60 changes: 60 additions & 0 deletions src/universal/service/HistoryService.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { createBrowserHistory } from 'history';
import { WINDOW_GLOBAL_PARAMS } from '../utils/constants';

let instance;

const setReferrer = referrer => {
if (process.env.BROWSER) {
window.ref = referrer;
}
};

export default class HistoryService {
constructor(historyKey) {
if (instance) {
return instance;
}

this.current = '';
this.previous = '';
this.history = null;
this.historyKey = historyKey;
this._listenCallback = this._listenCallback.bind(this);

this._selectHistoryKey();

if (process.env.BROWSER) {
this.current = window.location.href;
this.history = window[this.historyKey];

if (this.historyKey === historyKey) {
this.history.listen(this._listenCallback);
}
}

instance = this;
}

_listenCallback(location) {
if (!process.env.BROWSER) return;

this.previous = this.current;
this.current = `${window.location.origin}${location.pathname}${location.search}${location.hash}`;
setReferrer(this.previous);
}

_selectHistoryKey() {
if (!process.env.BROWSER) return;

// eslint-disable-next-line no-prototype-builtins
if (!window.hasOwnProperty(WINDOW_GLOBAL_PARAMS.HISTORY)) {
window[this.historyKey] = createBrowserHistory();
} else {
this.historyKey = WINDOW_GLOBAL_PARAMS.HISTORY;
}
}

getHistory() {
return this.history;
}
}
4 changes: 3 additions & 1 deletion src/universal/utils/constants.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
const appConfig = require('__APP_CONFIG__');
const voltranConfig = require('../../../voltran.config');

const WINDOW_GLOBAL_PARAMS = {
HISTORY: 'storefront.pwa.mobile.global.history'
HISTORY: 'storefront.pwa.mobile.global.history',
VOLTRAN_HISTORY: voltranConfig.historyKey || 'voltran.global.history'
};

const HTTP_STATUS_CODES = {
Expand Down

0 comments on commit e33858d

Please sign in to comment.