Repository URL to install this package:
|
Version:
0.0.13 ▾
|
/**
* @file React application middleware, supports server side rendering.
* @see https://reactjs.org/docs/react-dom-server.html#rendertostaticmarkup
*/
import { isString } from 'exotic';
import { oneRouter } from '@skava/router';
import { Shush } from '../deps/Shush';
// import { logger } from '../log'
import { fromReqResToRespondFromCacheExistence, deleteApolloCache } from '../caching';
import { renderUsingServerSideRendering } from './renderWithServerSide';
import { renderWithoutServerSide } from './renderWithoutServerSide';
import { respondError } from './responders';
function setOneRouterUrl(req) {
oneRouter.oneUrl = req.oneUrl;
oneRouter.urlFromExpress = req.oneUrl || {
full: 'webpack_hmr',
};
}
const log = new Shush();
async function reactApplicationMiddleware(req, res) {
const logger = req.log;
setOneRouterUrl(req);
/**
* @todo - probably want to add a header
*/
if (req.SHOULD_CACHE_SSR) {
const success = fromReqResToRespondFromCacheExistence(req, res);
if (success === true) {
return;
}
}
/**
* Ensure a nonce has been provided to us.
* @see server/middleware/security.js for more info.
*/
const nonce = res.locals.nonce;
if (!isString(nonce)) {
logger.warn('@todo - no nonce');
// throw new Error('A "nonce" value has not been attached to the res')
}
/**
* It's possible to disable SSR, which can be useful in development mode.
* In this case traditional client side only rendering will occur.
*
* @note - added `nocache`
*/
if (process.env.DISABLE_SSR === 'true' || oneRouter.oneUrl.full.includes('nossr')) {
logger.warn('[ssr] DISABLED! requestUrl:', oneRouter.urlFromExpress);
renderWithoutServerSide(res, nonce);
}
else {
logger.debug('[ssr] ==> Handling react route __WITH__ SSR');
logger.info('requestUrl', oneRouter.urlFromExpress);
try {
// @todo change to `shush`?
/**
* @todo we should probably just delete apollo cache after every req anyway?
* ^ maybe want to keep just like, categories?
*/
if (req.oneUrl.full.includes('nocache') === true) {
await deleteApolloCache();
}
log.unShush();
renderUsingServerSideRendering(req, res, nonce);
log.unShush();
}
catch (renderingException) {
log.unShush();
logger.error('[EXCEPTION_ALERT] [ssr] renderingException: ', renderingException);
respondError(res, renderingException);
}
}
}
export { reactApplicationMiddleware, reactApplicationMiddleware as reactApplication, renderUsingServerSideRendering as render, };
export default reactApplicationMiddleware;
//# sourceMappingURL=reactApplication.js.map