server.js 2.94 KB
const express = require('express');
const hbs = require('hbs');
const bodyParser = require('body-parser');
const chalk = require('chalk');
const _ = require('lodash');
const checkReport = require('../libs/check-report')
const logger = require('debug')('tester');
const config = require('../config.json');
const app = express();

hbs.registerPartials(__dirname + '/views/partials');
hbs.registerHelper('json', function(context) {
  return JSON.stringify(context, null, 2)
});


let currentScene = '';
const sceneData = {};
const dataReport = {};

app.set('view engine', 'hbs');
app.set('views', __dirname + '/views');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.post('/start-scene-case', (req, res) => {
  currentScene = req.body.scene;
  return res.status(200).end();
});
app.post('/stop-scene-case', (req, res) => {
  currentScene = '';
  try {
    const {notValidates, overLogs} = checkReport(req.body.scene, sceneData);

    dataReport[req.body.scene] = {
      notValidates, overLogs
    }

    if (notValidates.length) {
      return res.json({
        code: 400,
        data: {notValidates, overLogs},
        message: '验证失败'
      })
    }
    return res.json({
      code: 200,
      data: {notValidates, overLogs},
      message: '验证成功'
    })
  } catch (error) {
    logger(chalk.red('检查埋点报错:', error.message));
    return res.json({
      code: 400,
      data: {notValidates: [], overLogs: []},
      message: '验证失败'
    })
  }
  
});
app.get('/report', (req, res) => {
  const renderData = Object.keys(dataReport).map(scene => {
    return {
      scene,
      status: dataReport[scene].notValidates.length === 0,
      notValidates: dataReport[scene].notValidates,
      overLogs: dataReport[scene].overLogs
    }
  })

  res.locals = {data: renderData};

  res.render('report');
});
app.get('/report-not-validate', (req, res) => {
  const scene = req.query.scene;

  res.locals = {scene: scene, data: dataReport[scene].notValidates};
  res.render('report-not-validate');
});

app.get('/report-over-log', (req, res) => {
  const scene = req.query.scene;

  res.locals = {scene: scene, data: dataReport[scene].overLogs};
  res.render('report-over-log');
});
app.post('/yas_mobile', (req, res) => {
  const _mlogs = req.body._mlogs;

  if (_mlogs) {
    try {
      const data = JSON.parse(_mlogs);

      if (currentScene) {
        if (!sceneData[currentScene]) {
          sceneData[currentScene] = [];
        }
        if (data.events) {
          sceneData[currentScene] = sceneData[currentScene].concat(data.events);
        }
        _.each(data.events, evt => {
          logger(chalk.gray(`上报log, ${currentScene}, op: ${evt.op}`));
        })
      }
    } catch (error) {
      logger(chalk.red('上报解析错误', error.message));
    }
  } else {
    logger(chalk.red('上报无内容'));
  }
  res.send('')
});

app.listen(config.port, () => {
  logger(chalk.gray('reporter 启动成功'));
})