Skip to content

Commit

Permalink
ADD server side data functions and response setter
Browse files Browse the repository at this point in the history
  • Loading branch information
ahmetkuslular committed Feb 4, 2022
1 parent dd82862 commit f6a2827
Show file tree
Hide file tree
Showing 12 changed files with 251 additions and 76 deletions.
5 changes: 5 additions & 0 deletions config/string.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@ function replaceString() {
replace: normalizeUrl(voltranConfig.routing.requestConfigs),
flags: 'g'
},
{
search: '__V_PREVIEW_PAGES__',
replace: normalizeUrl(voltranConfig.routing.previewPages),
flags: 'g'
},
{
search: '@voltran/core',
replace: normalizeUrl(path.resolve(__dirname, '../src/index')),
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
"classnames": "2.2.6",
"clean-webpack-plugin": "1.0.0",
"cli-color": "^2.0.0",
"colors": "^1.4.0",
"compose-middleware": "5.0.0",
"compression": "^1.7.4",
"cookie-parser": "1.4.3",
Expand Down
9 changes: 4 additions & 5 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import withBaseComponent from './universal/partials/withBaseComponent';
import voltran from './universal/partials/withBaseComponent';
import { SERVICES } from './universal/utils/constants';
import { ClientApiManager, ServerApiManager } from './universal/core/api';

export default {
withBaseComponent,
SERVICES
};
export default voltran;
export { SERVICES, ClientApiManager, ServerApiManager };
57 changes: 50 additions & 7 deletions src/renderMultiple.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,39 @@ import { matchUrlInRouteConfigs } from './universal/core/route/routeUtils';
import Component from './universal/model/Component';
import Renderer from './universal/model/Renderer';
import Preview from './universal/components/Preview';
import { isRequestDispatcher, isPreview, isWithoutHTML } from './universal/service/RenderService';
import {
isRequestDispatcher,
isPreview,
isWithoutHTML,
isWithoutState,
getPreviewLayout
} from './universal/service/RenderService';
import metrics from './metrics';
import { HTTP_STATUS_CODES } from './universal/utils/constants';
import logger from './universal/utils/logger';

const previewPages = require('__V_PREVIEW_PAGES__');

const getRenderOptions = req => {
const isPreviewValue = isPreview(req.query) || false;
const isWithoutHTMLValue = isWithoutHTML(req.query) || false;
const isWithoutStateValue = isWithoutState(req.query) || false;

return {
isPreview: isPreviewValue,
isWithoutHTML: isWithoutHTMLValue,
isWithoutState: isWithoutStateValue
};
};

function getRenderer(name, req) {
const { query, cookies, url, headers, params } = req;
const path = `/${params?.path || ''}`;
const userAgent = headers['user-agent'];

const componentPath = Component.getComponentPath(name);
const routeInfo = matchUrlInRouteConfigs(componentPath);
const renderOptions = getRenderOptions(req);

if (routeInfo) {
const urlWithPath = url.replace('/', path);
Expand All @@ -26,6 +47,7 @@ function getRenderer(name, req) {
cookies,
url: urlWithPath,
userAgent,
...renderOptions
};

if (Component.isExist(componentPath)) {
Expand Down Expand Up @@ -177,11 +199,21 @@ async function getResponses(renderers) {
return responses;
}

async function getPreview(responses, requestCount) {
return Preview(
[...Object.keys(responses).map(name => responses[name].fullHtml)].join('\n'),
`${requestCount} request!`
);
async function getPreview(responses, requestCount, req) {
const layoutName = getPreviewLayout(req.query);
const { layouts } = previewPages.default;
let PreviewFile = Preview;

if (layouts[layoutName]) {
PreviewFile = layouts[layoutName];
}

const content = Object.keys(responses).map(name => {
const componentName = responses?.[name]?.activeComponent?.componentName ?? '';
return getLayoutWithClass(componentName, responses[name].fullHtml);
});

return PreviewFile([...content].join('\n'), `${requestCount} request!`);
}

const DEFAULT_PARTIALS = ['RequestDispatcher'];
Expand All @@ -199,6 +231,17 @@ export const getPartials = req => {
return partials;
};

function cr(condition, ok, cancel) {
return condition ? ok : cancel || '';
}

const getLayoutWithClass = (name, html, id = '', style = null) => {
const idAttr = cr(id !== '', `id=${id}`);
const styleAttr = cr(style !== null, `style=${style}`);

return `<div class="${name}" ${idAttr} ${styleAttr}>${html}</div>`;
};

const renderMultiple = async (req, res) => {
const partials = getPartials(req);

Expand Down Expand Up @@ -228,7 +271,7 @@ const renderMultiple = async (req, res) => {
const responses = await getResponses(renderers);

if (isPreview(req.query)) {
const preview = await getPreview(responses, requestCount);
const preview = await getPreview(responses, requestCount, req);
res.html(preview);
} else {
res.json(responses);
Expand Down
2 changes: 2 additions & 0 deletions src/universal/core/api/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export { default as ClientApiManager } from './ClientApiManagerCache';
export { default as ServerApiManager } from './ServerApiManagerCache';
35 changes: 20 additions & 15 deletions src/universal/model/Renderer.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
import ServerApiManagerCache from '../core/api/ServerApiManagerCache';
import omit from 'lodash/omit';
import { isPreview, renderComponent, renderLinksAndScripts } from '../service/RenderService';

const blacklistOutput = [
'componentName',
'fullWidth',
'isMobileComponent',
'isPreviewQuery',
'responseOptions'
];
export default class Renderer {
constructor(component, context) {
this.component = component;
Expand All @@ -13,44 +20,42 @@ export default class Renderer {
this.isPredefinedInitialStateSupported() &&
(process.env.BROWSER || (!process.env.BROWSER && !this.context.isWithoutState))
) {
this.servicesMap = this.getServicesMap();
this.servicesMap = this.getServicesWithMultiple();
this.winnerMap = {};
}
}

setInitialState(prepareInitialStateArgs) {
this.initialState = {
data: this.component.object.prepareInitialState(...prepareInitialStateArgs)
data: this.component.object.getInitialStateWithMultiple(...prepareInitialStateArgs)
};
}

isPredefinedInitialStateSupported() {
return this.component.object.getServicesMap && this.component.object.prepareInitialState;
}

getServicesMap() {
const services = this.component.object.services.map(
serviceName => ServerApiManagerCache[serviceName]
return (
this.component.object.getServicesWithMultiple &&
this.component.object.getInitialStateWithMultiple
);
}

const params = [...services, this.context];
return this.component.object.getServicesMap(...params);
getServicesWithMultiple() {
const options = { isServer: false };
return this.component.object.getServicesWithMultiple(this.context, options);
}

render() {
return new Promise(resolve => {
renderComponent(this.component, this.context, this.initialState).then(response => {
const { output, links, scripts, activeComponent, seoState, fullHtml } = response;
const { output, links, fullHtml, ...rest } = response;
const otherParams = omit(rest, blacklistOutput);
const html = renderLinksAndScripts(output, '', '');

resolve({
key: this.component.name,
value: {
html,
scripts,
style: links,
activeComponent,
seoState,
...otherParams,
...(isPreview(this.context?.query) && { fullHtml })
},
id: this.component.id
Expand Down
26 changes: 19 additions & 7 deletions src/universal/partials/Welcome/PartialList.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const Welcome = () => {
const { live = [], dev = [], page = [] } = groupBy(partials, item => item.status);

const renderItem = item => (
<ListItem>
<ListItem status={item.status}>
<Link href={item.previewUrl ? item.previewUrl : `${item.url}?preview`} target="_blank">
<Name>{item.name}</Name>
<Url>{item.url}</Url>
Expand All @@ -26,12 +26,24 @@ const Welcome = () => {
);
return (
<List>
<HeaderName>Live</HeaderName>
{live.map(item => renderItem(item))}
<HeaderName>Pages</HeaderName>
{page.map(item => renderItem(item))}
<HeaderName>Development</HeaderName>
{dev.map(item => renderItem(item))}
{live.length > 0 && (
<>
<HeaderName>Live</HeaderName>
{live.map(item => renderItem(item))}
</>
)}
{page.length > 0 && (
<>
<HeaderName>Pages</HeaderName>
{page.map(item => renderItem(item))}
</>
)}
{dev.length > 0 && (
<>
<HeaderName>Development</HeaderName>
{dev.map(item => renderItem(item))}
</>
)}
</List>
);
};
Expand Down
3 changes: 3 additions & 0 deletions src/universal/partials/Welcome/partials.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import components from '../../core/route/components';

const previewPages = require('__V_PREVIEW_PAGES__');

const partials = [];

Object.keys(components).forEach(path => {
Expand All @@ -10,5 +12,6 @@ Object.keys(components).forEach(path => {
status: info.status
});
});
partials.push(...previewPages.default.pages);

export default partials;
39 changes: 32 additions & 7 deletions src/universal/partials/Welcome/styled.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,15 @@ import styled from 'styled-components';

const STATUS_COLOR = {
live: '#8dc63f',
dev: '#FF6000'
dev: '#FF6000',
page: '#00abff'
};

export const List = styled.ul`
list-style: none;
margin: 0;
padding: 0;
margin-bottom: 20px;
`;

export const HeaderName = styled.div`
Expand All @@ -18,19 +21,41 @@ export const HeaderName = styled.div`

export const ListItem = styled.li`
padding: 20px;
border-radius: 2px;
background: white;
box-shadow: 0 2px 1px rgba(170, 170, 170, 0.25);
position: relative;
display: inline-block;
vertical-align: top;
height: 120px;
width: 320px;
margin: 10px;
cursor: pointer;
border-radius: 20px;
border: 1px solid ${({ status }) => (status && STATUS_COLOR[status]) || '#8dc63f'};
position: relative;
background-color: #fff;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
-webkit-transition: all 0.6s cubic-bezier(0.165, 0.84, 0.44, 1);
transition: all 0.6s cubic-bezier(0.165, 0.84, 0.44, 1);
:after {
content: '';
border-radius: 20px;
position: absolute;
z-index: -1;
top: 0;
left: 0;
width: 100%;
height: 100%;
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
opacity: 0;
-webkit-transition: all 0.6s cubic-bezier(0.165, 0.84, 0.44, 1);
transition: all 0.6s cubic-bezier(0.165, 0.84, 0.44, 1);
}
&:hover {
background: #efefef;
transform: scale(1.02, 1.02);
:after {
opacity: 1;
}
}
@media screen and (max-width: 600px) {
Expand Down Expand Up @@ -58,7 +83,7 @@ export const Link = styled.a`
`;

export const Name = styled.span`
font-weight: 400;
font-weight: 800;
display: block;
max-width: 80%;
font-size: 16px;
Expand Down
Loading

0 comments on commit f6a2827

Please sign in to comment.