All files utils.js

94.44% Statements 51/54
81.25% Branches 26/32
94.44% Functions 17/18
96% Lines 48/50
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 2052x 2x 2x 2x 2x   2x               2x     7x         3x 3x           5x   5x   5x 5x 5x                     10x                                 10x   9x         3x                                     11x   11x   11x 11x     11x                         9x 2x 2x     7x       7x 7x             1x         7x         7x                             4x       2x           9x 2x   7x     9x                             3x   1x   1x             1x           2x 2x 2x 2x 2x
var path = require("path");
var renderToString = require("react-dom/server").renderToString;
var React = require("react");
var StaticRouter = require("react-router-dom").StaticRouter;
var lib = require("./lib");
 
var httpCodes = {
    redirect: 301,
    ok: 200,
    notFound: 404,
    internalServerError: 500,
    notImplemented: 501
};
 
var pollInterval = 200;
 
function isRedirect(res) {
    return res.statusCode === httpCodes.redirect;
}
 
function setErrorStatus(res, e) {
 
    res.statusMessage = e.message || e;
    res.status(httpCodes.internalServerError);
 
}
 
function waitForTemplate(options) {
 
    return (new Promise(function(resolve) {
 
        var interval = setInterval(function() {
 
            Eif (options.fs.existsSync(options.templatePath)) {
                clearInterval(interval);
                resolve(options.fs.readFileSync(options.templatePath).toString());
            }
 
        }, pollInterval);
 
    }));
 
}
 
function renderHTML(config, options) {
 
    var parsedTemplate = options.template({
        component: config.component,
        error: config.error,
        html: config.html,
        initialProps: config.initialProps,
        store: config.store,
        renderProps: config.renderProps,
        req: config.req,
        res: config.res,
        template: config.template.replace(
            '<head>', // this should be the first script on a page so that others can pick it up
            '<head>' +
            '<script type="text/javascript">window["' + options.initialStateKey + '"] = ' + JSON.stringify(config.store ? config.store.getState() : undefined) + ';</script>' +
            '<script type="text/javascript">window["' + options.initialPropsKey + '"] = ' + JSON.stringify(config.initialProps) + ';</script>'
        )
    });
 
    if (typeof parsedTemplate !== 'string') throw new Error('Return type of options.template() has to be a string');
 
    return parsedTemplate;
 
}
 
function errorTemplate(config) {
    return (
        "<h1>" + httpCodes.internalServerError + " Server Error</h1>" +
        "<pre>" + (config.error.stack || config.error) + "</pre>"
    );
}
 
function defaultTemplate(config) {
 
    var error = config.error ? ('<div id="server-error">' + errorTemplate(config) + '</div>') : '';
 
    return config.template.replace(
        '<div id="root"></div>',
        error + '<div id="root">' + config.html + '</div>'
    );
 
}
 
function middleware(options, template, req, res) {
 
    var initialProps, context = {}; // these vars are passes all the way
 
    return (new Promise(function performRouting(resolve, reject) {
 
        ['app'].forEach((k) => {
            Iif (!options[k]) throw new Error('Mandatory option not defined: ' + k);
        });
 
        var initialHtml = renderToString(React.createElement(
            StaticRouter,
            {location: req.url, context: context},
            options.app({
                props: undefined,
                req: req,
                res: res,
                state: undefined
            })
        ));
 
        // console.log('Context', context);
 
        if (context.url) {
            res.redirect(httpCodes.redirect, context.url); //TODO Handle context.code
            return reject(new Error('Redirect'));
        }
 
        resolve(initialHtml);
 
    })).then(function getInitialPropsOfComponent() {
 
        return (new Promise(function(resolve) {
            resolve((context.getInitialProps) ? context.getInitialProps({
                location: context.location,
                req: req,
                res: res,
                store: context.store
            }) : null);
        }).catch(function(e) {
            return {initialError: e.message || e.toString()};
        }));
 
    }).then(function renderApp(props) {
 
        initialProps = props || {}; // client relies on truthy value of server-rendered props
 
        // console.log('Setting context initial props', initialProps);
        // console.log('Store state before rendering', context.store.getState());
 
        return {
            html: renderToString(React.createElement(
                StaticRouter,
                {location: req.url, context: context},
                options.app({
                    props: initialProps,
                    req: req,
                    res: res,
                    state: context.store ? context.store.getState() : undefined
                })
            ))
        };
 
    }).catch(function renderErrorHandler(e) {
 
        if (isRedirect(res)) throw e;
 
        // If we end up here it means server-side error that can't be handled by application
        // By returning an object we are recovering from error
        return {
            error: e
        };
 
    }).then(function renderAndSendHtml(result) {
 
        if (result.error) {
            setErrorStatus(res, result.error);
        } else {
            res.status(context.code || httpCodes.ok);
        }
 
        res.send(renderHTML(
            lib.extends({
                error: null,
                initialProps: initialProps,
                html: '',
                req: req,
                res: res,
                store: context.store,
                template: template
            }, result), // appends error or html
            options
        ));
 
    }).catch(function finalErrorHandler(e) {
 
        if (isRedirect(res)) return;
 
        setErrorStatus(res, e);
 
        res.send(errorTemplate({
            error: e,
            req: req,
            res: res,
            template: template
        }));
 
        return e; // re-throw to make it unhandled?
 
    });
 
}
 
exports.middleware = middleware;
exports.errorTemplate = errorTemplate;
exports.defaultTemplate = defaultTemplate;
exports.renderHTML = renderHTML;
exports.waitForTemplate = waitForTemplate;