matchMock.js 2.87 KB
Newer Older
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
1 2 3
const pathToRegexp = require('path-to-regexp');
const bodyParser = require('body-parser');

ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
4
const mockFile = require('./index');
5

ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
6 7
const BODY_PARSED_METHODS = ['post', 'put', 'patch'];

8
const debug = console.log;
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
9 10 11 12
function parseKey(key) {
  let method = 'get';
  let path = key;
  if (key.indexOf(' ') > -1) {
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
13 14 15
    const spliced = key.split(' ');
    method = spliced[0].toLowerCase();
    path = spliced[1]; // eslint-disable-line
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
16
  }
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
17
  const routerBasePath = process.env.NODE_ENV === 'dev' ? `${path}` : `/.netlify/functions${path}`;
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
18 19
  return {
    method,
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
20
    path: routerBasePath,
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
21 22 23 24
  };
}

function createHandler(method, path, handler) {
25 26 27 28 29 30 31 32
  return (req, res, next) => {
    function sendData() {
      if (typeof handler === 'function') {
        handler(req, res, next);
      } else {
        res.json(handler);
      }
    }
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
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
    if (BODY_PARSED_METHODS.includes(method)) {
      bodyParser.json({ limit: '5mb', strict: false })(req, res, () => {
        bodyParser.urlencoded({ limit: '5mb', extended: true })(req, res, () => {
          sendData();
        });
      });
    } else {
      sendData();
    }
  };
}

function normalizeConfig(config) {
  return Object.keys(config).reduce((memo, key) => {
    const handler = config[key];
    const { method, path } = parseKey(key);
    const keys = [];
    const re = pathToRegexp(path, keys);
    memo.push({
      method,
      path,
      re,
      keys,
      handler: createHandler(method, path, handler),
    });
    return memo;
  }, []);
}

const mockData = normalizeConfig(mockFile);

function matchMock(req) {
  const { path: exceptPath } = req;
  const exceptMethod = req.method.toLowerCase();
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
  function decodeParam(val) {
    if (typeof val !== 'string' || val.length === 0) {
      return val;
    }

    try {
      return decodeURIComponent(val);
    } catch (err) {
      if (err instanceof URIError) {
        err.message = `Failed to decode param ' ${val} '`;
        err.statusCode = 400;
        err.status = 400;
      }

      throw err;
    }
  }
  // eslint-disable-next-line no-restricted-syntax
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
85 86 87 88 89 90 91
  for (const mock of mockData) {
    const { method, re, keys } = mock;
    if (method === exceptMethod) {
      const match = re.exec(req.path);
      if (match) {
        const params = {};

92
        for (let i = 1; i < match.length; i += 1) {
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
93 94 95 96 97 98 99 100 101 102 103 104 105 106
          const key = keys[i - 1];
          const prop = key.name;
          const val = decodeParam(match[i]);

          if (val !== undefined || !hasOwnProperty.call(params, prop)) {
            params[prop] = val;
          }
        }
        req.params = params;
        return mock;
      }
    }
  }

107
  return mockData.filter(({ method, re }) => method === exceptMethod && re.test(exceptPath))[0];
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
108 109 110 111 112 113 114
}
module.exports = (req, res, next) => {
  const match = matchMock(req);
  if (match) {
    debug(`mock matched: [${match.method}] ${match.path}`);
    return match.handler(req, res, next);
  }
115
  return next();
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
116
};