mock平台

commons.js 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  1. const fs = require('fs-extra');
  2. const path = require('path');
  3. const yapi = require('../yapi.js');
  4. const sha1 = require('sha1');
  5. const logModel = require('../models/log.js');
  6. const projectModel = require('../models/project.js');
  7. const interfaceColModel = require('../models/interfaceCol.js');
  8. const interfaceCaseModel = require('../models/interfaceCase.js');
  9. const interfaceModel = require('../models/interface.js');
  10. const userModel = require('../models/user.js');
  11. const followModel = require('../models/follow.js');
  12. const json5 = require('json5');
  13. const _ = require('underscore');
  14. const Ajv = require('ajv');
  15. const Mock = require('mockjs');
  16. const ejs = require('easy-json-schema');
  17. const jsf = require('json-schema-faker');
  18. const { schemaValidator } = require('../../common/utils');
  19. const http = require('http');
  20. jsf.extend ('mock', function () {
  21. return {
  22. mock: function (xx) {
  23. return Mock.mock (xx);
  24. }
  25. };
  26. });
  27. const defaultOptions = {
  28. failOnInvalidTypes: false,
  29. failOnInvalidFormat: false
  30. };
  31. // formats.forEach(item => {
  32. // item = item.name;
  33. // jsf.format(item, () => {
  34. // if (item === 'mobile') {
  35. // return jsf.random.randexp('^[1][34578][0-9]{9}$');
  36. // }
  37. // return Mock.mock('@' + item);
  38. // });
  39. // });
  40. exports.schemaToJson = function(schema, options = {}) {
  41. Object.assign(options, defaultOptions);
  42. jsf.option(options);
  43. let result;
  44. try {
  45. result = jsf(schema);
  46. } catch (err) {
  47. result = err.message;
  48. }
  49. jsf.option(defaultOptions);
  50. return result;
  51. };
  52. exports.resReturn = (data, num, errmsg) => {
  53. num = num || 0;
  54. return {
  55. errcode: num,
  56. errmsg: errmsg || '成功!',
  57. data: data
  58. };
  59. };
  60. exports.log = (msg, type) => {
  61. if (!msg) {
  62. return;
  63. }
  64. type = type || 'log';
  65. let f;
  66. switch (type) {
  67. case 'log':
  68. f = console.log; // eslint-disable-line
  69. break;
  70. case 'warn':
  71. f = console.warn; // eslint-disable-line
  72. break;
  73. case 'error':
  74. f = console.error; // eslint-disable-line
  75. break;
  76. default:
  77. f = console.log; // eslint-disable-line
  78. break;
  79. }
  80. f(type + ':', msg);
  81. let date = new Date();
  82. let year = date.getFullYear();
  83. let month = date.getMonth() + 1;
  84. let logfile = path.join(yapi.WEBROOT_LOG, year + '-' + month + '.log');
  85. if (typeof msg === 'object') {
  86. if (msg instanceof Error) msg = msg.message;
  87. else msg = JSON.stringify(msg);
  88. }
  89. // let data = (new Date).toLocaleString() + '\t|\t' + type + '\t|\t' + msg + '\n';
  90. let data = `[ ${new Date().toLocaleString()} ] [ ${type} ] ${msg}\n`;
  91. fs.writeFileSync(logfile, data, {
  92. flag: 'a'
  93. });
  94. };
  95. exports.fileExist = filePath => {
  96. try {
  97. return fs.statSync(filePath).isFile();
  98. } catch (err) {
  99. return false;
  100. }
  101. };
  102. exports.time = () => {
  103. return Date.parse(new Date()) / 1000;
  104. };
  105. exports.fieldSelect = (data, field) => {
  106. if (!data || !field || !Array.isArray(field)) {
  107. return null;
  108. }
  109. var arr = {};
  110. field.forEach(f => {
  111. typeof data[f] !== 'undefined' && (arr[f] = data[f]);
  112. });
  113. return arr;
  114. };
  115. exports.rand = (min, max) => {
  116. return Math.floor(Math.random() * (max - min) + min);
  117. };
  118. exports.json_parse = json => {
  119. try {
  120. return json5.parse(json);
  121. } catch (e) {
  122. return json;
  123. }
  124. };
  125. exports.randStr = () => {
  126. return Math.random()
  127. .toString(36)
  128. .substr(2);
  129. };
  130. exports.getIp = ctx => {
  131. let ip;
  132. try {
  133. ip = ctx.ip.match(/\d+.\d+.\d+.\d+/) ? ctx.ip.match(/\d+.\d+.\d+.\d+/)[0] : 'localhost';
  134. } catch (e) {
  135. ip = null;
  136. }
  137. return ip;
  138. };
  139. exports.generatePassword = (password, passsalt) => {
  140. return sha1(password + sha1(passsalt));
  141. };
  142. exports.expireDate = day => {
  143. let date = new Date();
  144. date.setTime(date.getTime() + day * 86400000);
  145. return date;
  146. };
  147. exports.sendMail = (options, cb) => {
  148. if (!yapi.mail) return false;
  149. options.subject = options.subject ? options.subject + '-YApi 平台' : 'YApi 平台';
  150. cb =
  151. cb ||
  152. function(err) {
  153. if (err) {
  154. yapi.commons.log('send mail ' + options.to + ' error,' + err.message, 'error');
  155. } else {
  156. yapi.commons.log('send mail ' + options.to + ' success');
  157. }
  158. };
  159. try {
  160. yapi.mail.sendMail(
  161. {
  162. from: yapi.WEBCONFIG.mail.from,
  163. to: options.to,
  164. subject: options.subject,
  165. html: options.contents
  166. },
  167. cb
  168. );
  169. } catch (e) {
  170. yapi.commons.log(e.message, 'error');
  171. console.error(e.message); // eslint-disable-line
  172. }
  173. };
  174. exports.validateSearchKeyword = keyword => {
  175. if (/^\*|\?|\+|\$|\^|\\|\.$/.test(keyword)) {
  176. return false;
  177. }
  178. return true;
  179. };
  180. exports.filterRes = (list, rules) => {
  181. return list.map(item => {
  182. let filteredRes = {};
  183. rules.forEach(rule => {
  184. if (typeof rule == 'string') {
  185. filteredRes[rule] = item[rule];
  186. } else if (typeof rule == 'object') {
  187. filteredRes[rule.alias] = item[rule.key];
  188. }
  189. });
  190. return filteredRes;
  191. });
  192. };
  193. exports.handleVarPath = (pathname, params) => {
  194. function insertParams(name) {
  195. if (!_.find(params, { name: name })) {
  196. params.push({
  197. name: name,
  198. desc: ''
  199. });
  200. }
  201. }
  202. if (!pathname) return;
  203. if (pathname.indexOf(':') !== -1) {
  204. let paths = pathname.split('/'),
  205. name,
  206. i;
  207. for (i = 1; i < paths.length; i++) {
  208. if (paths[i] && paths[i][0] === ':') {
  209. name = paths[i].substr(1);
  210. insertParams(name);
  211. }
  212. }
  213. }
  214. pathname.replace(/\{(.+?)\}/g, function(str, match) {
  215. insertParams(match);
  216. });
  217. };
  218. /**
  219. * 验证一个 path 是否合法
  220. * path第一位必需为 /, path 只允许由 字母数字-/_:.{}= 组成
  221. */
  222. exports.verifyPath = path => {
  223. // if (/^\/[a-zA-Z0-9\-\/_:!\.\{\}\=]*$/.test(path)) {
  224. // return true;
  225. // } else {
  226. // return false;
  227. // }
  228. return /^\/[a-zA-Z0-9\-\/_:!\.\{\}\=]*$/.test(path);
  229. };
  230. /**
  231. * 沙盒执行 js 代码
  232. * @sandbox Object context
  233. * @script String script
  234. * @return sandbox
  235. *
  236. * @example let a = sandbox({a: 1}, 'a=2')
  237. * a = {a: 2}
  238. */
  239. exports.sandbox = (sandbox, script) => {
  240. const vm = require('vm');
  241. sandbox = sandbox || {};
  242. script = new vm.Script(script);
  243. const context = new vm.createContext(sandbox);
  244. script.runInContext(context, {
  245. timeout: 3000
  246. });
  247. return sandbox;
  248. };
  249. function trim(str) {
  250. if (!str) {
  251. return str;
  252. }
  253. str = str + '';
  254. return str.replace(/(^\s*)|(\s*$)/g, '');
  255. }
  256. function ltrim(str) {
  257. if (!str) {
  258. return str;
  259. }
  260. str = str + '';
  261. return str.replace(/(^\s*)/g, '');
  262. }
  263. function rtrim(str) {
  264. if (!str) {
  265. return str;
  266. }
  267. str = str + '';
  268. return str.replace(/(\s*$)/g, '');
  269. }
  270. exports.trim = trim;
  271. exports.ltrim = ltrim;
  272. exports.rtrim = rtrim;
  273. /**
  274. * 处理请求参数类型,String 字符串去除两边空格,Number 使用parseInt 转换为数字
  275. * @params Object {a: ' ab ', b: ' 123 '}
  276. * @keys Object {a: 'string', b: 'number'}
  277. * @return Object {a: 'ab', b: 123}
  278. */
  279. exports.handleParams = (params, keys) => {
  280. if (!params || typeof params !== 'object' || !keys || typeof keys !== 'object') {
  281. return false;
  282. }
  283. for (var key in keys) {
  284. var filter = keys[key];
  285. if (params[key]) {
  286. switch (filter) {
  287. case 'string':
  288. params[key] = trim(params[key] + '');
  289. break;
  290. case 'number':
  291. params[key] = !isNaN(params[key]) ? parseInt(params[key], 10) : 0;
  292. break;
  293. default:
  294. params[key] = trim(params + '');
  295. }
  296. }
  297. }
  298. return params;
  299. };
  300. exports.validateParams = (schema2, params) => {
  301. const flag = schema2.closeRemoveAdditional;
  302. const ajv = new Ajv({
  303. allErrors: true,
  304. coerceTypes: true,
  305. useDefaults: true,
  306. removeAdditional: flag ? false : true
  307. });
  308. var localize = require('ajv-i18n');
  309. delete schema2.closeRemoveAdditional;
  310. const schema = ejs(schema2);
  311. schema.additionalProperties = flag ? true : false;
  312. const validate = ajv.compile(schema);
  313. let valid = validate(params);
  314. let message = '请求参数 ';
  315. if (!valid) {
  316. localize.zh(validate.errors);
  317. message += ajv.errorsText(validate.errors, { separator: '\n' });
  318. }
  319. return {
  320. valid: valid,
  321. message: message
  322. };
  323. };
  324. exports.saveLog = logData => {
  325. try {
  326. let logInst = yapi.getInst(logModel);
  327. let data = {
  328. content: logData.content,
  329. type: logData.type,
  330. uid: logData.uid,
  331. username: logData.username,
  332. typeid: logData.typeid,
  333. data: logData.data
  334. };
  335. logInst.save(data).then();
  336. } catch (e) {
  337. yapi.commons.log(e, 'error'); // eslint-disable-line
  338. }
  339. };
  340. /**
  341. *
  342. * @param {*} router router
  343. * @param {*} baseurl base_url_path
  344. * @param {*} routerController controller
  345. * @param {*} path routerPath
  346. * @param {*} method request_method , post get put delete ...
  347. * @param {*} action controller action_name
  348. * @param {*} ws enable ws
  349. */
  350. exports.createAction = (router, baseurl, routerController, action, path, method, ws) => {
  351. router[method](baseurl + path, async ctx => {
  352. let inst = new routerController(ctx);
  353. try {
  354. await inst.init(ctx);
  355. ctx.params = Object.assign({}, ctx.request.query, ctx.request.body, ctx.params);
  356. if (inst.schemaMap && typeof inst.schemaMap === 'object' && inst.schemaMap[action]) {
  357. let validResult = yapi.commons.validateParams(inst.schemaMap[action], ctx.params);
  358. if (!validResult.valid) {
  359. return (ctx.body = yapi.commons.resReturn(null, 400, validResult.message));
  360. }
  361. }
  362. if (inst.$auth === true) {
  363. await inst[action].call(inst, ctx);
  364. } else {
  365. if (ws === true) {
  366. ctx.ws.send('请登录...');
  367. } else {
  368. ctx.body = yapi.commons.resReturn(null, 40011, '请登录...');
  369. }
  370. }
  371. } catch (err) {
  372. ctx.body = yapi.commons.resReturn(null, 40011, '服务器出错...');
  373. yapi.commons.log(err, 'error');
  374. }
  375. });
  376. };
  377. /**
  378. *
  379. * @param {*} params 接口定义的参数
  380. * @param {*} val 接口case 定义的参数值
  381. */
  382. function handleParamsValue(params, val) {
  383. let value = {};
  384. try {
  385. params = params.toObject();
  386. } catch (e) {}
  387. if (params.length === 0 || val.length === 0) {
  388. return params;
  389. }
  390. val.forEach(item => {
  391. value[item.name] = item;
  392. });
  393. params.forEach((item, index) => {
  394. if (!value[item.name] || typeof value[item.name] !== 'object') return null;
  395. params[index].value = value[item.name].value;
  396. if (!_.isUndefined(value[item.name].enable)) {
  397. params[index].enable = value[item.name].enable;
  398. }
  399. });
  400. return params;
  401. }
  402. exports.handleParamsValue = handleParamsValue;
  403. exports.getCaseList = async function getCaseList(id) {
  404. const caseInst = yapi.getInst(interfaceCaseModel);
  405. const colInst = yapi.getInst(interfaceColModel);
  406. const projectInst = yapi.getInst(projectModel);
  407. const interfaceInst = yapi.getInst(interfaceModel);
  408. let resultList = await caseInst.list(id, 'all');
  409. let colData = await colInst.get(id);
  410. for (let index = 0; index < resultList.length; index++) {
  411. let result = resultList[index].toObject();
  412. let data = await interfaceInst.get(result.interface_id);
  413. if (!data) {
  414. await caseInst.del(result._id);
  415. continue;
  416. }
  417. let projectData = await projectInst.getBaseInfo(data.project_id);
  418. result.path = projectData.basepath + data.path;
  419. result.method = data.method;
  420. result.title = data.title;
  421. result.req_body_type = data.req_body_type;
  422. result.req_headers = handleParamsValue(data.req_headers, result.req_headers);
  423. result.res_body_type = data.res_body_type;
  424. result.req_body_form = handleParamsValue(data.req_body_form, result.req_body_form);
  425. result.req_query = handleParamsValue(data.req_query, result.req_query);
  426. result.req_params = handleParamsValue(data.req_params, result.req_params);
  427. resultList[index] = result;
  428. }
  429. resultList = resultList.sort((a, b) => {
  430. return a.index - b.index;
  431. });
  432. let ctxBody = yapi.commons.resReturn(resultList);
  433. ctxBody.colData = colData;
  434. return ctxBody;
  435. };
  436. function convertString(variable) {
  437. if (variable instanceof Error) {
  438. return variable.name + ': ' + variable.message;
  439. }
  440. try {
  441. if(variable && typeof variable === 'string'){
  442. return variable;
  443. }
  444. return JSON.stringify(variable, null, ' ');
  445. } catch (err) {
  446. return variable || '';
  447. }
  448. }
  449. exports.runCaseScript = async function runCaseScript(params, colId, interfaceId) {
  450. const colInst = yapi.getInst(interfaceColModel);
  451. let colData = await colInst.get(colId);
  452. const logs = [];
  453. const context = {
  454. assert: require('assert'),
  455. status: params.response.status,
  456. body: params.response.body,
  457. header: params.response.header,
  458. records: params.records,
  459. params: params.params,
  460. log: msg => {
  461. logs.push('log: ' + convertString(msg));
  462. }
  463. };
  464. let result = {};
  465. try {
  466. if(colData.checkHttpCodeIs200){
  467. let status = +params.response.status;
  468. if(status !== 200){
  469. throw ('Http status code 不是 200,请检查(该规则来源于于 [测试集->通用规则配置] )')
  470. }
  471. }
  472. if(colData.checkResponseField.enable){
  473. if(params.response.body[colData.checkResponseField.name] != colData.checkResponseField.value){
  474. throw (`返回json ${colData.checkResponseField.name} 值不是${colData.checkResponseField.value},请检查(该规则来源于于 [测试集->通用规则配置] )`)
  475. }
  476. }
  477. if(colData.checkResponseSchema){
  478. const interfaceInst = yapi.getInst(interfaceModel);
  479. let interfaceData = await interfaceInst.get(interfaceId);
  480. if(interfaceData.res_body_is_json_schema && interfaceData.res_body){
  481. let schema = JSON.parse(interfaceData.res_body);
  482. let result = schemaValidator(schema, context.body)
  483. if(!result.valid){
  484. throw (`返回Json 不符合 response 定义的数据结构,原因: ${result.message}
  485. 数据结构如下:
  486. ${JSON.stringify(schema,null,2)}`)
  487. }
  488. }
  489. }
  490. if(colData.checkScript.enable){
  491. let globalScript = colData.checkScript.content;
  492. // script 是断言
  493. if (globalScript) {
  494. logs.push('执行脚本:' + globalScript)
  495. result = yapi.commons.sandbox(context, globalScript);
  496. }
  497. }
  498. let script = params.script;
  499. // script 是断言
  500. if (script) {
  501. logs.push('执行脚本:' + script)
  502. result = yapi.commons.sandbox(context, script);
  503. }
  504. result.logs = logs;
  505. return yapi.commons.resReturn(result);
  506. } catch (err) {
  507. logs.push(convertString(err));
  508. result.logs = logs;
  509. logs.push(err.name + ': ' + err.message)
  510. return yapi.commons.resReturn(result, 400, err.name + ': ' + err.message);
  511. }
  512. };
  513. exports.getUserdata = async function getUserdata(uid, role) {
  514. role = role || 'dev';
  515. let userInst = yapi.getInst(userModel);
  516. let userData = await userInst.findById(uid);
  517. if (!userData) {
  518. return null;
  519. }
  520. return {
  521. role: role,
  522. uid: userData._id,
  523. username: userData.username,
  524. email: userData.email
  525. };
  526. };
  527. // 处理mockJs脚本
  528. exports.handleMockScript = function(script, context) {
  529. let sandbox = {
  530. header: context.ctx.header,
  531. query: context.ctx.query,
  532. body: context.ctx.request.body,
  533. mockJson: context.mockJson,
  534. params: Object.assign({}, context.ctx.query, context.ctx.request.body),
  535. resHeader: context.resHeader,
  536. httpCode: context.httpCode,
  537. delay: context.httpCode,
  538. Random: Mock.Random
  539. };
  540. sandbox.cookie = {};
  541. context.ctx.header.cookie &&
  542. context.ctx.header.cookie.split(';').forEach(function(Cookie) {
  543. var parts = Cookie.split('=');
  544. sandbox.cookie[parts[0].trim()] = (parts[1] || '').trim();
  545. });
  546. sandbox = yapi.commons.sandbox(sandbox, script);
  547. sandbox.delay = isNaN(sandbox.delay) ? 0 : +sandbox.delay;
  548. context.mockJson = sandbox.mockJson;
  549. context.resHeader = sandbox.resHeader;
  550. context.httpCode = sandbox.httpCode;
  551. context.delay = sandbox.delay;
  552. };
  553. exports.createWebAPIRequest = function(ops) {
  554. return new Promise(function(resolve, reject) {
  555. let req = '';
  556. let http_client = http.request(
  557. {
  558. host: ops.hostname,
  559. method: 'GET',
  560. port: ops.port,
  561. path: ops.path
  562. },
  563. function(res) {
  564. res.on('error', function(err) {
  565. reject(err);
  566. });
  567. res.setEncoding('utf8');
  568. if (res.statusCode != 200) {
  569. reject({message: 'statusCode != 200'});
  570. } else {
  571. res.on('data', function(chunk) {
  572. req += chunk;
  573. });
  574. res.on('end', function() {
  575. resolve(req);
  576. });
  577. }
  578. }
  579. );
  580. http_client.on('error', (e) => {
  581. reject({message: `request error: ${e.message}`});
  582. });
  583. http_client.end();
  584. });
  585. }