all files / lib/ app.js

100% Statements 29/29
100% Branches 7/7
100% Functions 3/3
100% Lines 29/29
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      13× 13× 13× 13×               13× 13× 13×   13× 12× 12×                
'use strict';
 
const path       = require('path');
const caller     = require('caller');
const express    = require('express');
const bodyParser = require('body-parser');
const morgan     = require('morgan');
const cors       = require('cors');
 
global.requireModule = function (modulePath) {
    modulePath = path.resolve(path.dirname(caller()), modulePath);
    let mod = require(modulePath);
    delete require.cache[require.resolve(modulePath)];
    return mod;
}
 
module.exports = function (dataPath) {
  let app = express();
 
  app.use(cors({
      origin: true,
      credentials: true
  }));
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({ extended: false }));
  app.use(morgan('dev'));
  app.disable('x-powered-by');
 
  app.all('*', function(req, res) {
    let mock = requireModule(dataPath);
    let method = req.method;
    let pathName = req.path;
 
    if(mock && mock[pathName] && mock[pathName][method]) {
      let configItem = mock[pathName][method];
      if(typeof(configItem) === 'function') {
        configItem(req, res);
      } else {
        res.send(configItem);
      }
    } else {
      res.status(404).end();
    }
  });
  
  return app;
};