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, context) => { let props = {...params}; if (apiInfo.params) { _.each(apiInfo.params, (v, k) => { let paramItem = params[k]; if (v.alias) { if (v.alias === 'uid') { if (context && context.user && context.user.uid) { paramItem = context.user.uid; } } } 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 props; }; module.exports = { getParams };