applyMock.js 1.5 KB
Newer Older
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 49 50 51 52 53 54 55 56 57 58 59 60 61
const createProxy = require('http-proxy-middleware');
const forEach = require('lodash/forEach');
const assert = require('assert');

const parseKey = (key) => {
  let method = 'get';
  let path = key;

  if (key.indexOf(' ') > -1) {
    const splited = key.split(' ');
    method = splited[0].toLowerCase();
    path = splited[1];
  }

  return { method, path };
};

const makeProxy = (method, path, target) => {
  const filter = (pathname, req) => {
    return path.test(pathname) && req.method === method.toUpperCase();
  };
  return createProxy(filter, { target });
};

const createMockHandler = (value) => {
  return function mockHandler(...args) {
    const res = args[1];
    if (typeof value === 'function') {
      value(...args);
    } else {
      res.json(value);
    }
  };
};

module.exports = (app, mock) => {
  forEach(mock, (value, key) => {
    const parsedkey = parseKey(key);
    assert(
      typeof value === 'function' ||
      typeof value === 'object' ||
      typeof value === 'string',
      `mock value of ${key} should be function or object or string, but got ${typeof value}`,
    );
    if (typeof value === 'string') {
      let path = parsedkey.path;
      if (/\(.+\)/.test(parsedkey.path)) {
        path = new RegExp(`^${parsedkey.path}$`);
      }
      app.use(
        path,
        makeProxy(parsedkey.method, path, value),
      );
    } else {
      app[parsedkey.method](
        parsedkey.path,
        createMockHandler(value),
      );
    }
  });
};