ssr.js 7.25 KB
const fs = require('fs');
const path = require('path');
const url = require('url');
const _ = require('lodash');
const os = require('os');
const md5 = require('yoho-md5');
const pkg = require('../../package.json');
const routes = require('../../config/ssr-routes');
const redis = require('../../utils/redis');
const routeEncode = require('../../utils/route-encode');
const {createBundleRenderer} = require('vue-server-renderer');
const Handlebars = require('handlebars');
const logger = global.yoho.logger;
const config = global.yoho.config;

const isProd = process.env.NODE_ENV === 'production';
const isDev = process.env.NODE_ENV === 'development' || !process.env.NODE_ENV;

let renderer;
let serverBundle;
let degradeHtml;

const hbs = fs.readFileSync(path.join(__dirname, '../views/index.hbs'), 'utf-8');

const template = Handlebars.compile(hbs);

if (!isDev) {

  degradeHtml = fs.readFileSync(path.join(__dirname, '../../degrade.html'), 'utf-8');

  serverBundle = require('../../manifest.server.json');
  const clientManifest = require('../../manifest.json');

  renderer = createBundleRenderer(serverBundle, {
    runInNewContext: false,
    clientManifest,
    inject: false
  });
}

const REG_SCRIPT = /src="([^"]+)"/g;

const asyncLoadScripts = (renderScripts) => {
  let match;
  const scripts = [];

  while ((match = REG_SCRIPT.exec(renderScripts))) {
    scripts.push({
      src: match[1],
      index: scripts.length
    });
  }

  return scripts;
};

const getContext = (req) => {
  let res = {
    url: req.url,
    title: '',
    user: req.user,
    env: {
      udid: req.yoho.udid,
      isApp: req.yoho.isApp,
      isiOS: req.yoho.isiOS,
      isAndroid: req.yoho.isAndroid,
      isYohoApp: req.yoho.isYohoApp,
      clientIp: req.yoho.clientIp,
      version: req.query.app_version || pkg.version,
      osVersion: req.query.os_version || '',
      buildId: req.app.locals.buildId
    },
    ua: req.get('user-agent'),
    hostname: os.hostname(),
    route: `[${req.method}]${_.get(req, 'route.path', '')}`, // 请求路由
    udid: _.get(req, 'cookies.udid', 'yoho'),
    path: `[${req.method}]${routeEncode.getRouter(req)}`,
  };

  if (!isProd) {
    res.env.unProd = true;
  }

  return res;
};

const handlerError = (err = {}, req, res, next) => {
  if (err.code === 404) {
    return res.redirect('/error/404');
  } else if (err.code === 500) {
    return res.redirect('/error/500');
  }
  return next(err);
};

const getCacheKey = (req, route) => {
  const urlObj = url.parse(req.url);
  let ck = urlObj.pathname;

  if (route.query) {
    const qks = Object.keys(route.query);

    ck += `?${qks.map(qk => `${qk}=${req.query && req.query[qk] || ''}`).join('&')}`;
  }
  ck += `|${pkg.version}`;

  return md5(ck);
};

const ThreeDays = 3 * 24 * 60 * 60 * 1000;

const render = (route) => {
  return async(req, res, next) => {
    try {
      if (!route.cache) {
        res.set({
          'Cache-Control': 'no-cache',
          Pragma: 'no-cache',
          Expires: (new Date(1900, 0, 1, 0, 0, 0, 0)).toUTCString()
        });
      } else {
        res.set({
          'Cache-Control': 'max-age=' + route.cacheTime || 60
        });
      }
      res.setHeader('X-YOHO-Version', pkg.version);

      if (req.query && req.query.SRC_ID) {
        res.cookie('SRC_ID', req.query.SRC_ID, {
          domain: 'yohobuy.com',
          path: '/',
          maxAge: ThreeDays
        });
      }

      const isDegrade = _.get(req.app.locals.wap, 'webapp.degrade', false);

      logger.info(JSON.stringify({
        type: 'ssr_page_access',
        app: config.appName,
        ip: req.yoho.clientIp,
        path: req.url,
        pageName: _.get(route, 'pageName', 'unknown'),
        uid: req.user.uid,
        udid: req.cookies.udid || '',
        clientType: req.yoho.clientType || '',
        ua: req.get('user-agent'),
        time: new Date()
      }));

      if (isDegrade) {
        return res.send(degradeHtml);
      }
      const ck = getCacheKey(req, route);

      if (config.useCache && route.cache && ck) {
        const html = await redis.getAsync(ck);

        if (html) {
          logger.debug(`cached ${req.url}`);
          res.setHeader('X-YOHO-Cached', 'HIT');
          return res.send(html);
        }
        res.setHeader('X-YOHO-Cached', 'MISS');
      }
      let context = getContext(req);

      renderer.renderToString(context, (err, html) => {
        if (err) {
          return handlerError(err, req, res, next);
        }
        let styles = context.renderStyles();
        let scripts = context.renderScripts();
        let resources = context.renderResourceHints();
        const states = context.renderState();
        let asyncScripts;
        let zk = {
          webperf: _.get(req.app.locals.wap, 'open.webperf', false),
          asyncJs: _.get(req.app.locals.wap, 'webapp.ios-async-js', true)
        };

        if (req.yoho.isiOS && zk.asyncJs) {
          asyncScripts = asyncLoadScripts(scripts);
        }

        const result = template({
          title: context.title || '',
          html,
          styles,
          scripts,
          asyncScripts,
          resources,
          states,
          zk,
          routeHash: routeEncode.getRouter(req)
        });

        if (config.useCache && route.cache && ck) {
          redis.setex(ck, route.cacheTime || 60, result);
        }
        return res.send(result);
      });
    } catch (error) {
      return next(error);
    }
  };
};
const devRender = (route) => {
  return async(req, res, next) => {
    try {
      res.setHeader('X-YOHO-Version', pkg.version);
      const ck = getCacheKey(req, route);

      if (route.accessLog) {
        logger.info(`[page access] ${req.yoho.clientIp} | ${req.url} | uid:${req.user.uid} | ${new Date()}`);
      }

      // return require('request-promise')({
      //   url: 'http://m.yohobuy.com:6005/degrade.html'
      // }).pipe(res);
      if (config.useCache && route.cache && ck) {
        const html = await redis.getAsync(ck);

        if (html) {
          logger.info(`cached ${req.url}`);
          res.setHeader('X-YOHO-Cached', 'HIT');
          return res.send(html);
        }
        res.setHeader('X-YOHO-Cached', 'MISS');
      }

      if (req.query && req.query.SRC_ID) {
        res.cookie('SRC_ID', req.query.SRC_ID, {
          domain: 'yohobuy.com',
          path: '/',
          maxAge: ThreeDays
        });
      }

      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) {
            let err = msg.err;

            try {
              err = JSON.parse(msg.err);
            } catch (error) {} // eslint-disable-line
            return handlerError(err, req, res, next);
          }
          if (config.useCache && route.cache && ck) {
            redis.setex(ck, route.cacheTime || 60, msg.html);
          }
          return res.end(msg.html);
        }
      };

      process.on('message', event);
    } catch (error) {
      return next(error);
    }
  };
};

const router = require('express').Router(); //eslint-disable-line

_.each(routes, r => {
  if (!r.disable) {
    router.get(r.route, isDev ? devRender(r) : render(r));
  }
});

exports.ssrRender = isDev ? devRender({}) : render({});

exports.routers = router;