Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Split antui chakra #338

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion build.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ const config = {
process.env.WEBSITE_URL || `${__SERVER_PROTOCOL__}://${__SERVER_HOST__}:${__WEB_DEV_SERVER_PORT__}`,
__BACKEND_URL__:
process.env.LOCAL_BACKEND_URL || `${__SERVER_PROTOCOL__}://${__SERVER_HOST__}:${__WEB_SERVER_PORT__}`,
__CHAKRA__: false,
__ANTUI__: false,
};

console.log('---CONFIG', config);
module.exports = config;
1 change: 1 addition & 0 deletions servers/backend-server/build.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,5 @@ const config = {
__FRONTEND_BUILD_DIR__: process.env.FRONTEND_BUILD_DIR || '../frontend-server/dist/web',
};

console.log('---CONFIG', config);
module.exports = config;
3 changes: 3 additions & 0 deletions servers/frontend-server/build.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ const config = {
__GRAPHQL_URL__: process.env.GRAPHQL_URL || '/graphql',
__API_URL__: process.env.API_URL || '/graphql',
__FRONTEND_BUILD_DIR__: process.env.FRONTEND_BUILD_DIR || './dist/web',
__CHAKRA__: process.env.CHAKRA === 'true' || false,
__ANTUI__: process.env.ANTUI === 'true' || false,
};

console.log('---CONFIG', config);
module.exports = config;
5 changes: 2 additions & 3 deletions servers/frontend-server/src/app/Main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import { PersistGate } from 'redux-persist/integration/react';
import { persistStore } from 'redux-persist';
import { createBrowserHistory } from 'history';
import { HelmetProvider } from 'react-helmet-async';

import { createReduxStore } from '../config/redux-config';
import { createClientContainer } from '../config/client.service';
import modules, { MainRoute } from '../modules';
Expand All @@ -30,8 +29,8 @@ export class Main extends React.Component<{}, {}> {
<ApolloProvider client={client}>
<MainRoute />
</ApolloProvider>
</ConnectedRouter>,
)}
</ConnectedRouter>
)}
</PersistGate>
</ReduxProvider>
</HelmetProvider>
Expand Down
90 changes: 45 additions & 45 deletions servers/frontend-server/src/app/MainChakra.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,62 +8,62 @@ import { persistStore } from 'redux-persist';
import { createBrowserHistory } from 'history';
import { HelmetProvider } from 'react-helmet-async';
import { CacheProvider } from '@emotion/react';

import createEmotionCache from '../common/createEmotionCache';
import { createReduxStore } from '../config/redux-config';
import { createClientContainer } from '../config/client.service';
import modules, { MainRoute } from '../modules';

const { apolloClient: client } = createClientContainer();

const history = createBrowserHistory();
const { store } = createReduxStore(history);
const cache = createEmotionCache();

export class Main extends React.Component<{}, {}> {
public render() {
if (__SSR__) {
let persistor = persistStore(store);
return (
<HelmetProvider>
<CacheProvider value={cache}>
<Provider store={store}>
<ApolloProvider client={client}>
<PersistGate loading={null} persistor={persistor}>
{() => (
{modules.getWrappedRoot(
<ConnectedRouter history={history}>
<MainRoute />
</ConnectedRouter>,
)}
)}
</PersistGate>
</ApolloProvider>
</Provider>
</CacheProvider>
</HelmetProvider>
const WithChakra = () => {
if (__CHAKRA__) {
const cache = createEmotionCache();
return (
<CacheProvider value={cache}>
{modules.getWrappedRoot(
<ConnectedRouter history={history}>
<MainRoute />
</ConnectedRouter>,
)}
</CacheProvider>
);
} else {
return
modules.getWrappedRoot(
<ConnectedRouter history={history}>
<MainRoute />
</ConnectedRouter>,
);
} else {
let persistor = persistStore(store);
return (
<HelmetProvider>
<CacheProvider value={cache}>
<Provider store={store}>
<ApolloProvider client={client}>
<PersistGate persistor={persistor}>
{modules.getWrappedRoot(
<ConnectedRouter history={history}>
<MainRoute />
</ConnectedRouter>,
)}
</PersistGate>
</ApolloProvider>
</Provider>
</CacheProvider>
</HelmetProvider>
);
}
}
}

const WithPersistGate = () => {
let persistor = persistStore(store);
if (__SSR__) {
return (
<PersistGate loading={null} persistor={persistor}>
{() => <WithChakra />}
</PersistGate>
);
} else {
return (
<PersistGate persistor={persistor}>
<WithChakra />
</PersistGate>
);
}
}

const Main = () => (
<HelmetProvider>
<Provider store={store}>
<ApolloProvider client={client}>
<WithPersistGate />
</ApolloProvider>
</Provider>
</HelmetProvider>
);

export default Main;
37 changes: 37 additions & 0 deletions servers/frontend-server/src/backend/middlewares/website.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import path from 'path';
import { logger } from '@cdm-logger/server';

const getServerSideRenderer = async () => {
let renderer;
if (__CHAKRA__) {
if (__ANTUI__) {
renderer = await import('../website-chakra-antui');
} else {
renderer = await import('../website-chakra');
}
} else {
renderer = await import('../website-antui');
}

return renderer.default;
}

export const websiteMiddleware = async (req, res, next) => {
try {
if (req.path.indexOf('.') < 0 && __SSR__) {
const renderServerSide = await getServerSideRenderer();
if (renderServerSide) {
return await renderServerSide(req, res);
}
next();
} else if (req.path.indexOf('.') < 0 && !__SSR__ && req.method === 'GET' && !__DEV__) {
logger.debug('FRONEND_BUILD_DIR with index.html');
res.sendFile(path.resolve(__FRONTEND_BUILD_DIR__, 'index.html'));
} else {
next();
}
} catch (e) {
logger.error('RENDERING ERROR:', e);
return next(e);
}
};
2 changes: 1 addition & 1 deletion servers/frontend-server/src/backend/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import * as path from 'path';
import * as url from 'url';
import 'isomorphic-fetch';
import { logger } from '@cdm-logger/server';
import { websiteMiddleware } from './website-chakra-antui';
import { websiteMiddleware } from './middlewares/website';
import { corsMiddleware } from './middlewares/cors';
import { errorMiddleware } from './middlewares/error';
import { config } from '../config';
Expand Down
168 changes: 75 additions & 93 deletions servers/frontend-server/src/backend/website-antui.tsx
100755 → 100644
Original file line number Diff line number Diff line change
Expand Up @@ -20,104 +20,86 @@ import clientModules, { MainRoute } from '../modules';
let assetMap;
const antdCache = createAntdCache();

async function renderServerSide(req, res) {
try {
const { apolloClient: client } = createClientContainer();
export default async function renderServerSide(req, res) {
try {
const { apolloClient: client } = createClientContainer();

let context: { pageNotFound?: boolean; url?: string } = { pageNotFound: false };
const history = createMemoryHistory({ initialEntries: [req.url] });
const { store } = createReduxStore(history);
let context: { pageNotFound?: boolean; url?: string } = { pageNotFound: false };
const history = createMemoryHistory({ initialEntries: [req.url] });
const { store } = createReduxStore(history);

const extractor = new ChunkExtractor({
statsFile: path.resolve(__FRONTEND_BUILD_DIR__, 'loadable-stats.json'),
entrypoints: ['index'],
publicPath: !__DEV__ && __CDN_URL__ ? __CDN_URL__ : '/',
});
const extractor = new ChunkExtractor({
statsFile: path.resolve(__FRONTEND_BUILD_DIR__, 'loadable-stats.json'),
entrypoints: ['index'],
publicPath: !__DEV__ && __CDN_URL__ ? __CDN_URL__ : '/',
});

const helmetContext = {} as FilledContext;
const Root = (
<ChunkExtractorManager extractor={extractor}>
<HelmetProvider context={helmetContext}>
<StyleProvider cache={antdCache}>
<ReduxProvider store={store}>
<ApolloProvider client={client}>
{clientModules.getWrappedRoot(
<StaticRouter location={req.url} context={context}>
<MainRoute />
</StaticRouter>,
)}
</ApolloProvider>
</ReduxProvider>
</StyleProvider>
</HelmetProvider>
</ChunkExtractorManager>
);
const helmetContext = {} as FilledContext;
const Root = (
<ChunkExtractorManager extractor={extractor}>
<HelmetProvider context={helmetContext}>
<StyleProvider cache={antdCache}>
<ReduxProvider store={store}>
<ApolloProvider client={client}>
{clientModules.getWrappedRoot(
<StaticRouter location={req.url} context={context}>
<MainRoute />
</StaticRouter>,
)}
</ApolloProvider>
</ReduxProvider>
</StyleProvider>
</HelmetProvider>
</ChunkExtractorManager>
);

try {
await getDataFromTree(Root);
} catch (e: any) {
console.log('Apollo Error! Rendering result anyways');
console.log(e);
}
const content = ReactDOMServer.renderToString(Root);
try {
await getDataFromTree(Root);
} catch (e: any) {
console.log('Apollo Error! Rendering result anyways');
console.log(e);
}

if (context.pageNotFound === true) {
res.status(404);
}
const content = ReactDOMServer.renderToString(Root);
if (context.pageNotFound === true) {
res.status(404);
}


if (context.url) {
res.writeHead(301, { Location: context.url });
res.end();
} else {
if (__DEV__ || !assetMap) {
assetMap = JSON.parse(fs.readFileSync(path.join(__FRONTEND_BUILD_DIR__, 'assets.json')).toString());
}
// data
const apolloState = Object.assign({}, client.extract());
const reduxState = Object.assign({}, store.getState());
const env = {
...publicEnv,
};
// styles
let styleSheet = extractStyle(antdCache);
// html page
const page = (
<Html
content={content}
state={apolloState}
assetMap={assetMap}
helmet={helmetContext.helmet}
extractor={extractor}
env={env}
reduxState={reduxState}
scriptsInserts={clientModules.scriptsInserts}
stylesInserts={clientModules.stylesInserts}
/>
);
let pageContent = ReactDOMServer.renderToStaticMarkup(page);
pageContent = pageContent.replace(/__STYLESHEET__/, styleSheet);
res.status(200);
res.send(`<!doctype html>\n${pageContent}`);
res.end();
}
} catch (err) {
logger.error('SERVER SIDE RENDER failed due to (%j) ', err.message);
logger.debug(err);
if (context.url) {
res.writeHead(301, { Location: context.url });
res.end();
} else {
if (__DEV__ || !assetMap) {
assetMap = JSON.parse(fs.readFileSync(path.join(__FRONTEND_BUILD_DIR__, 'assets.json')).toString());
}
// data
const apolloState = { ...client.extract() };
const reduxState = { ...store.getState() };
const env = { ...publicEnv };
// styles
const styleSheet = extractStyle(antdCache);
// Html Page
const page = (
<Html
content={content}
state={apolloState}
assetMap={assetMap}
helmet={helmetContext.helmet}
extractor={extractor}
env={env}
reduxState={reduxState}
scriptsInserts={clientModules.scriptsInserts}
stylesInserts={clientModules.stylesInserts}
/>
);
let pageContent = ReactDOMServer.renderToStaticMarkup(page);
pageContent = pageContent.replace(/__STYLESHEET__/, styleSheet);
res.status(200);
res.send(`<!doctype html>\n${pageContent}`);
res.end();
}
} catch (err) {
logger.error('SERVER SIDE RENDER failed due to (%j) ', err.message);
logger.debug(err);
}
}
export const websiteMiddleware = async (req, res, next) => {
try {
if (req.path.indexOf('.') < 0 && __SSR__) {
return await renderServerSide(req, res);
} else if (req.path.indexOf('.') < 0 && !__SSR__ && req.method === 'GET' && !__DEV__) {
logger.debug('FRONEND_BUILD_DIR with index.html');
res.sendFile(path.resolve(__FRONTEND_BUILD_DIR__, 'index.html'));
} else {
next();
}
} catch (e) {
logger.error('RENDERING ERROR:', e);
return next(e);
}
};
Loading