check-params.js 1.42 KB
const _ = require('lodash');

const getType = fn => {
  const match = fn && fn.toString().match(/^\s*function (\w+)/);

  return match ? match[1] : '';
};

const simpleCheckRE = /^(String|Number|Boolean|Function|Symbol)$/;

const assetType = (value, type) => {
  const expectedType = getType(type);
  let valid;

  if (simpleCheckRE.test(expectedType)) {
    const t = typeof value;

    valid = t === expectedType.toLowerCase();

    // for primitive wrapper objects
    if (!valid && t === 'object') {
      valid = value instanceof type;
    }
    if (!valid && expectedType.toLowerCase() === 'number') {
      const parseNumber = parseInt(value, 10);

      valid = parseNumber || parseNumber === 0;
    }
  } else if (expectedType === 'Object') {
    valid = value.toString() === '[object Object]';
  } else if (expectedType === 'Array') {
    valid = Array.isArray(value);
  } else {
    valid = value instanceof type;
  }
  return valid;
};

const getParams = (params, apiInfo) => {
  let props = {};

  if (apiInfo.params) {
    _.each(apiInfo.params, (v, k) => {
      const paramItem = params[k];

      if (!paramItem) {
        if (v.require) {
          throw Error(`${k} params is not undefined`);
        }
        return;
      }
      if (!assetType(paramItem, v.type)) {
        throw Error(`${k} params is not ${getType(v.type)}`);
      }
      props[k] = paramItem;
    });
  }
  return params;
};

module.exports = {
  getParams,
};