ssr.js 1.86 KB
const fs = require('fs');
const rp = require('request-promise');
const path = require('path');
const pkg = require('../../package.json');
const {createBundleRenderer} = require('vue-server-renderer');

const isDev = process.env.NODE_ENV === 'development' || !process.env.NODE_ENV;
let renderer;
let template = fs.readFileSync(path.join(__dirname, '../../src/index.html'), 'utf-8');

const getContext = (req) => {
    return {
        url: req.url,
        title: 'BLK!',
        env: {
            isApp: req.yoho.isApp,
            isiOS: req.yoho.isiOS,
            isAndroid: req.yoho.isAndroid,
            isYohoBuy: req.yoho.isYohoBuy,
            channel: req.yoho.channel
        }
    };
};

const render = (req, res, next) => {
    let context = getContext(req);

    renderer.renderToString(context, (err, html) => {
        if (err) {
            return next(err);
        }
        return res.send(html);
    });
};

if (!isDev) {
    Promise.all([
        rp(`https://cdn.yoho.cn/yohoblk-wap/bundle/yoho-ssr-server-${pkg.version}.json`, {json: true}),
        rp(`https://cdn.yoho.cn/yohoblk-wap/bundle/yoho-ssr-client-${pkg.version}.json`, {json: true}),
    ]).then(results => {
        renderer = createBundleRenderer(results[0], {
            runInNewContext: false,
            template,
            clientManifest: results[1]
        });
    });
}


const ssrRender = isDev ? (req, res, next) => {
    let context = getContext(req);

    process.send({action: 'ssr_request', context});
    let event = msg => {
        process.removeListener('message', event);
        if (msg.action === 'ssr_request') {
            if (msg.err) {
                return next(msg.err);
            }
            return res.end(msg.html);
        }
    };

    process.on('message', event);
} : render;



module.exports = app => {
    app.get(/\/product\/pro_([\d]+)_([\d]+)\/(.*).html/, ssrRender);
};