mock平台

interface.js 39KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231
  1. const interfaceModel = require('../models/interface.js');
  2. const interfaceCatModel = require('../models/interfaceCat.js');
  3. const interfaceCaseModel = require('../models/interfaceCase.js');
  4. const followModel = require('../models/follow.js');
  5. const groupModel = require('../models/group.js');
  6. const _ = require('underscore');
  7. const url = require('url');
  8. const baseController = require('./base.js');
  9. const yapi = require('../yapi.js');
  10. const userModel = require('../models/user.js');
  11. const projectModel = require('../models/project.js');
  12. const jsondiffpatch = require('jsondiffpatch');
  13. const formattersHtml = jsondiffpatch.formatters.html;
  14. const showDiffMsg = require('../../common/diff-view.js');
  15. const mergeJsonSchema = require('../../common/mergeJsonSchema');
  16. const fs = require('fs-extra');
  17. const path = require('path');
  18. // const annotatedCss = require("jsondiffpatch/public/formatters-styles/annotated.css");
  19. // const htmlCss = require("jsondiffpatch/public/formatters-styles/html.css");
  20. function handleHeaders(values){
  21. let isfile = false,
  22. isHavaContentType = false;
  23. if (values.req_body_type === 'form') {
  24. values.req_body_form.forEach(item => {
  25. if (item.type === 'file') {
  26. isfile = true;
  27. }
  28. });
  29. values.req_headers.map(item => {
  30. if (item.name === 'Content-Type') {
  31. item.value = isfile ? 'multipart/form-data' : 'application/x-www-form-urlencoded';
  32. isHavaContentType = true;
  33. }
  34. });
  35. if (isHavaContentType === false) {
  36. values.req_headers.unshift({
  37. name: 'Content-Type',
  38. value: isfile ? 'multipart/form-data' : 'application/x-www-form-urlencoded'
  39. });
  40. }
  41. } else if (values.req_body_type === 'json') {
  42. values.req_headers
  43. ? values.req_headers.map(item => {
  44. if (item.name === 'Content-Type') {
  45. item.value = 'application/json';
  46. isHavaContentType = true;
  47. }
  48. })
  49. : [];
  50. if (isHavaContentType === false) {
  51. values.req_headers = values.req_headers || [];
  52. values.req_headers.unshift({
  53. name: 'Content-Type',
  54. value: 'application/json'
  55. });
  56. }
  57. }
  58. }
  59. class interfaceController extends baseController {
  60. constructor(ctx) {
  61. super(ctx);
  62. this.Model = yapi.getInst(interfaceModel);
  63. this.catModel = yapi.getInst(interfaceCatModel);
  64. this.projectModel = yapi.getInst(projectModel);
  65. this.caseModel = yapi.getInst(interfaceCaseModel);
  66. this.followModel = yapi.getInst(followModel);
  67. this.userModel = yapi.getInst(userModel);
  68. this.groupModel = yapi.getInst(groupModel);
  69. const minLengthStringField = {
  70. type: 'string',
  71. minLength: 1
  72. };
  73. const addAndUpCommonField = {
  74. desc: 'string',
  75. status: 'string',
  76. req_query: [
  77. {
  78. name: 'string',
  79. value: 'string',
  80. example: 'string',
  81. desc: 'string',
  82. required: 'string'
  83. }
  84. ],
  85. req_headers: [
  86. {
  87. name: 'string',
  88. value: 'string',
  89. example: 'string',
  90. desc: 'string',
  91. required: 'string'
  92. }
  93. ],
  94. req_body_type: 'string',
  95. req_params: [
  96. {
  97. name: 'string',
  98. example: 'string',
  99. desc: 'string'
  100. }
  101. ],
  102. req_body_form: [
  103. {
  104. name: 'string',
  105. type: {
  106. type: 'string'
  107. },
  108. example: 'string',
  109. desc: 'string',
  110. required: 'string'
  111. }
  112. ],
  113. req_body_other: 'string',
  114. res_body_type: 'string',
  115. res_body: 'string',
  116. custom_field_value: 'string',
  117. api_opened: 'boolean',
  118. req_body_is_json_schema: 'string',
  119. res_body_is_json_schema: 'string',
  120. markdown: 'string',
  121. tag: 'array'
  122. };
  123. this.schemaMap = {
  124. add: Object.assign(
  125. {
  126. '*project_id': 'number',
  127. '*path': minLengthStringField,
  128. '*title': minLengthStringField,
  129. '*method': minLengthStringField,
  130. '*catid': 'number'
  131. },
  132. addAndUpCommonField
  133. ),
  134. up: Object.assign(
  135. {
  136. '*id': 'number',
  137. project_id: 'number',
  138. path: minLengthStringField,
  139. title: minLengthStringField,
  140. method: minLengthStringField,
  141. catid: 'number',
  142. switch_notice: 'boolean',
  143. message: minLengthStringField
  144. },
  145. addAndUpCommonField
  146. ),
  147. save: Object.assign(
  148. {
  149. project_id: 'number',
  150. catid: 'number',
  151. title: minLengthStringField,
  152. path: minLengthStringField,
  153. method: minLengthStringField,
  154. message: minLengthStringField,
  155. dataSync: 'string'
  156. },
  157. addAndUpCommonField
  158. )
  159. };
  160. }
  161. /**
  162. * 添加项目分组
  163. * @interface /interface/add
  164. * @method POST
  165. * @category interface
  166. * @foldnumber 10
  167. * @param {Number} project_id 项目id,不能为空
  168. * @param {String} title 接口标题,不能为空
  169. * @param {String} path 接口请求路径,不能为空
  170. * @param {String} method 请求方式
  171. * @param {Array} [req_headers] 请求的header信息
  172. * @param {String} [req_headers[].name] 请求的header信息名
  173. * @param {String} [req_headers[].value] 请求的header信息值
  174. * @param {Boolean} [req_headers[].required] 是否是必须,默认为否
  175. * @param {String} [req_headers[].desc] header描述
  176. * @param {String} [req_body_type] 请求参数方式,有["form", "json", "text", "xml"]四种
  177. * @param {Array} [req_params] name, desc两个参数
  178. * @param {Mixed} [req_body_form] 请求参数,如果请求方式是form,参数是Array数组,其他格式请求参数是字符串
  179. * @param {String} [req_body_form[].name] 请求参数名
  180. * @param {String} [req_body_form[].value] 请求参数值,可填写生成规则(mock)。如@email,随机生成一条email
  181. * @param {String} [req_body_form[].type] 请求参数类型,有["text", "file"]两种
  182. * @param {String} [req_body_other] 非form类型的请求参数可保存到此字段
  183. * @param {String} [res_body_type] 相应信息的数据格式,有["json", "text", "xml"]三种
  184. * @param {String} [res_body] 响应信息,可填写任意字符串,如果res_body_type是json,则会调用mock功能
  185. * @param {String} [desc] 接口描述
  186. * @returns {Object}
  187. * @example ./api/interface/add.json
  188. */
  189. async add(ctx) {
  190. let params = ctx.params;
  191. if (!this.$tokenAuth) {
  192. let auth = await this.checkAuth(params.project_id, 'project', 'edit');
  193. if (!auth) {
  194. return (ctx.body = yapi.commons.resReturn(null, 40033, '没有权限'));
  195. }
  196. }
  197. params.method = params.method || 'GET';
  198. params.res_body_is_json_schema = _.isUndefined(params.res_body_is_json_schema)
  199. ? false
  200. : params.res_body_is_json_schema;
  201. params.req_body_is_json_schema = _.isUndefined(params.req_body_is_json_schema)
  202. ? false
  203. : params.req_body_is_json_schema;
  204. params.method = params.method.toUpperCase();
  205. params.req_params = params.req_params || [];
  206. params.res_body_type = params.res_body_type ? params.res_body_type.toLowerCase() : 'json';
  207. let http_path = url.parse(params.path, true);
  208. if (!yapi.commons.verifyPath(http_path.pathname)) {
  209. return (ctx.body = yapi.commons.resReturn(
  210. null,
  211. 400,
  212. 'path第一位必需为 /, 只允许由 字母数字-/_:.! 组成'
  213. ));
  214. }
  215. handleHeaders(params)
  216. params.query_path = {};
  217. params.query_path.path = http_path.pathname;
  218. params.query_path.params = [];
  219. Object.keys(http_path.query).forEach(item => {
  220. params.query_path.params.push({
  221. name: item,
  222. value: http_path.query[item]
  223. });
  224. });
  225. let checkRepeat = await this.Model.checkRepeat(params.project_id, params.path, params.method);
  226. if (checkRepeat > 0) {
  227. return (ctx.body = yapi.commons.resReturn(
  228. null,
  229. 40022,
  230. '已存在的接口:' + params.path + '[' + params.method + ']'
  231. ));
  232. }
  233. let data = Object.assign(params, {
  234. uid: this.getUid(),
  235. add_time: yapi.commons.time(),
  236. up_time: yapi.commons.time()
  237. });
  238. yapi.commons.handleVarPath(params.path, params.req_params);
  239. if (params.req_params.length > 0) {
  240. data.type = 'var';
  241. data.req_params = params.req_params;
  242. } else {
  243. data.type = 'static';
  244. }
  245. // 新建接口的人成为项目dev 如果不存在的话
  246. // 命令行导入时无法获知导入接口人的信息,其uid 为 999999
  247. let uid = this.getUid();
  248. if (this.getRole() !== 'admin' && uid !== 999999) {
  249. let userdata = await yapi.commons.getUserdata(uid, 'dev');
  250. // 检查一下是否有这个人
  251. let check = await this.projectModel.checkMemberRepeat(params.project_id, uid);
  252. if (check === 0 && userdata) {
  253. await this.projectModel.addMember(params.project_id, [userdata]);
  254. }
  255. }
  256. let result = await this.Model.save(data);
  257. yapi.emitHook('interface_add', result).then();
  258. this.catModel.get(params.catid).then(cate => {
  259. let username = this.getUsername();
  260. let title = `<a href="/user/profile/${this.getUid()}">${username}</a> 为分类 <a href="/project/${
  261. params.project_id
  262. }/interface/api/cat_${params.catid}">${cate.name}</a> 添加了接口 <a href="/project/${
  263. params.project_id
  264. }/interface/api/${result._id}">${data.title}</a> `;
  265. yapi.commons.saveLog({
  266. content: title,
  267. type: 'project',
  268. uid: this.getUid(),
  269. username: username,
  270. typeid: params.project_id
  271. });
  272. this.projectModel.up(params.project_id, { up_time: new Date().getTime() }).then();
  273. });
  274. ctx.body = yapi.commons.resReturn(result);
  275. }
  276. /**
  277. * 保存接口数据,如果接口存在则更新数据,如果接口不存在则添加数据
  278. * @interface /interface/save
  279. * @method post
  280. * @category interface
  281. * @foldnumber 10
  282. * @param {Number} project_id 项目id,不能为空
  283. * @param {String} title 接口标题,不能为空
  284. * @param {String} path 接口请求路径,不能为空
  285. * @param {String} method 请求方式
  286. * @param {Array} [req_headers] 请求的header信息
  287. * @param {String} [req_headers[].name] 请求的header信息名
  288. * @param {String} [req_headers[].value] 请求的header信息值
  289. * @param {Boolean} [req_headers[].required] 是否是必须,默认为否
  290. * @param {String} [req_headers[].desc] header描述
  291. * @param {String} [req_body_type] 请求参数方式,有["form", "json", "text", "xml"]四种
  292. * @param {Array} [req_params] name, desc两个参数
  293. * @param {Mixed} [req_body_form] 请求参数,如果请求方式是form,参数是Array数组,其他格式请求参数是字符串
  294. * @param {String} [req_body_form[].name] 请求参数名
  295. * @param {String} [req_body_form[].value] 请求参数值,可填写生成规则(mock)。如@email,随机生成一条email
  296. * @param {String} [req_body_form[].type] 请求参数类型,有["text", "file"]两种
  297. * @param {String} [req_body_other] 非form类型的请求参数可保存到此字段
  298. * @param {String} [res_body_type] 相应信息的数据格式,有["json", "text", "xml"]三种
  299. * @param {String} [res_body] 响应信息,可填写任意字符串,如果res_body_type是json,则会调用mock功能
  300. * @param {String} [desc] 接口描述
  301. * @returns {Object}
  302. */
  303. async save(ctx) {
  304. let params = ctx.params;
  305. if (!this.$tokenAuth) {
  306. let auth = await this.checkAuth(params.project_id, 'project', 'edit');
  307. if (!auth) {
  308. return (ctx.body = yapi.commons.resReturn(null, 40033, '没有权限'));
  309. }
  310. }
  311. params.method = params.method || 'GET';
  312. params.method = params.method.toUpperCase();
  313. let http_path = url.parse(params.path, true);
  314. if (!yapi.commons.verifyPath(http_path.pathname)) {
  315. return (ctx.body = yapi.commons.resReturn(
  316. null,
  317. 400,
  318. 'path第一位必需为 /, 只允许由 字母数字-/_:.! 组成'
  319. ));
  320. }
  321. let result = await this.Model.getByPath(params.project_id, params.path, params.method, '_id res_body');
  322. if (result.length > 0) {
  323. result.forEach(async item => {
  324. params.id = item._id;
  325. // console.log(this.schemaMap['up'])
  326. let validParams = Object.assign({}, params)
  327. let validResult = yapi.commons.validateParams(this.schemaMap['up'], validParams);
  328. if (validResult.valid) {
  329. let data = {};
  330. data.params = validParams;
  331. if(params.res_body_is_json_schema && params.dataSync === 'good'){
  332. try{
  333. let new_res_body = yapi.commons.json_parse(params.res_body)
  334. let old_res_body = yapi.commons.json_parse(item.res_body)
  335. data.params.res_body = JSON.stringify(mergeJsonSchema(old_res_body, new_res_body),null,2);
  336. }catch(err){}
  337. }
  338. await this.up(data);
  339. } else {
  340. return (ctx.body = yapi.commons.resReturn(null, 400, validResult.message));
  341. }
  342. });
  343. } else {
  344. let validResult = yapi.commons.validateParams(this.schemaMap['add'], params);
  345. if (validResult.valid) {
  346. let data = {};
  347. data.params = params;
  348. await this.add(data);
  349. } else {
  350. return (ctx.body = yapi.commons.resReturn(null, 400, validResult.message));
  351. }
  352. }
  353. ctx.body = yapi.commons.resReturn(result);
  354. // return ctx.body = yapi.commons.resReturn(null, 400, 'path第一位必需为 /, 只允许由 字母数字-/_:.! 组成');
  355. }
  356. /**
  357. * 获取项目分组
  358. * @interface /interface/get
  359. * @method GET
  360. * @category interface
  361. * @foldnumber 10
  362. * @param {Number} id 接口id,不能为空
  363. * @returns {Object}
  364. * @example ./api/interface/get.json
  365. */
  366. async get(ctx) {
  367. let params = ctx.params;
  368. if (!params.id) {
  369. return (ctx.body = yapi.commons.resReturn(null, 400, '接口id不能为空'));
  370. }
  371. try {
  372. let result = await this.Model.get(params.id);
  373. if(this.$tokenAuth){
  374. if(params.project_id !== result.project_id){
  375. ctx.body = yapi.commons.resReturn(null, 400, 'token有误')
  376. return;
  377. }
  378. }
  379. // console.log('result', result);
  380. if (!result) {
  381. return (ctx.body = yapi.commons.resReturn(null, 490, '不存在的'));
  382. }
  383. let userinfo = await this.userModel.findById(result.uid);
  384. let project = await this.projectModel.getBaseInfo(result.project_id);
  385. if (project.project_type === 'private') {
  386. if ((await this.checkAuth(project._id, 'project', 'view')) !== true) {
  387. return (ctx.body = yapi.commons.resReturn(null, 406, '没有权限'));
  388. }
  389. }
  390. yapi.emitHook('interface_get', result).then();
  391. result = result.toObject();
  392. if (userinfo) {
  393. result.username = userinfo.username;
  394. }
  395. ctx.body = yapi.commons.resReturn(result);
  396. } catch (e) {
  397. ctx.body = yapi.commons.resReturn(null, 402, e.message);
  398. }
  399. }
  400. /**
  401. * 接口列表
  402. * @interface /interface/list
  403. * @method GET
  404. * @category interface
  405. * @foldnumber 10
  406. * @param {Number} project_id 项目id,不能为空
  407. * @param {Number} page 当前页
  408. * @param {Number} limit 每一页限制条数
  409. * @returns {Object}
  410. * @example ./api/interface/list.json
  411. */
  412. async list(ctx) {
  413. let project_id = ctx.params.project_id;
  414. let page = ctx.request.query.page || 1,
  415. limit = ctx.request.query.limit || 10;
  416. let status = ctx.request.query.status,
  417. tag = ctx.request.query.tag;
  418. let project = await this.projectModel.getBaseInfo(project_id);
  419. if (!project) {
  420. return (ctx.body = yapi.commons.resReturn(null, 407, '不存在的项目'));
  421. }
  422. if (project.project_type === 'private') {
  423. if ((await this.checkAuth(project._id, 'project', 'view')) !== true) {
  424. return (ctx.body = yapi.commons.resReturn(null, 406, '没有权限'));
  425. }
  426. }
  427. if (!project_id) {
  428. return (ctx.body = yapi.commons.resReturn(null, 400, '项目id不能为空'));
  429. }
  430. try {
  431. let result, count;
  432. if (limit === 'all') {
  433. result = await this.Model.list(project_id);
  434. count = await this.Model.listCount({project_id});
  435. } else {
  436. let option = {project_id};
  437. if (status) {
  438. if (Array.isArray(status)) {
  439. option.status = {"$in": status};
  440. } else {
  441. option.status = status;
  442. }
  443. }
  444. if (tag) {
  445. if (Array.isArray(tag)) {
  446. option.tag = {"$in": tag};
  447. } else {
  448. option.tag = tag;
  449. }
  450. }
  451. result = await this.Model.listByOptionWithPage(option, page, limit);
  452. count = await this.Model.listCount(option);
  453. }
  454. ctx.body = yapi.commons.resReturn({
  455. count: count,
  456. total: Math.ceil(count / limit),
  457. list: result
  458. });
  459. yapi.emitHook('interface_list', result).then();
  460. } catch (err) {
  461. ctx.body = yapi.commons.resReturn(null, 402, err.message);
  462. }
  463. }
  464. async downloadCrx(ctx) {
  465. let filename = 'crossRequest.zip';
  466. let dataBuffer = yapi.fs.readFileSync(
  467. yapi.path.join(yapi.WEBROOT, 'static/attachment/cross-request.zip')
  468. );
  469. ctx.set('Content-disposition', 'attachment; filename=' + filename);
  470. ctx.set('Content-Type', 'application/zip');
  471. ctx.body = dataBuffer;
  472. }
  473. async listByCat(ctx) {
  474. let catid = ctx.request.query.catid;
  475. let page = ctx.request.query.page || 1,
  476. limit = ctx.request.query.limit || 10;
  477. let status = ctx.request.query.status,
  478. tag = ctx.request.query.tag;
  479. if (!catid) {
  480. return (ctx.body = yapi.commons.resReturn(null, 400, 'catid不能为空'));
  481. }
  482. try {
  483. let catdata = await this.catModel.get(catid);
  484. let project = await this.projectModel.getBaseInfo(catdata.project_id);
  485. if (project.project_type === 'private') {
  486. if ((await this.checkAuth(project._id, 'project', 'view')) !== true) {
  487. return (ctx.body = yapi.commons.resReturn(null, 406, '没有权限'));
  488. }
  489. }
  490. let option = {catid}
  491. if (status) {
  492. if (Array.isArray(status)) {
  493. option.status = {"$in": status};
  494. } else {
  495. option.status = status;
  496. }
  497. }
  498. if (tag) {
  499. if (Array.isArray(tag)) {
  500. option.tag = {"$in": tag};
  501. } else {
  502. option.tag = tag;
  503. }
  504. }
  505. let result = await this.Model.listByOptionWithPage(option, page, limit);
  506. let count = await this.Model.listCount(option);
  507. ctx.body = yapi.commons.resReturn({
  508. count: count,
  509. total: Math.ceil(count / limit),
  510. list: result
  511. });
  512. } catch (err) {
  513. ctx.body = yapi.commons.resReturn(null, 402, err.message + '1');
  514. }
  515. }
  516. async listByMenu(ctx) {
  517. let project_id = ctx.params.project_id;
  518. if (!project_id) {
  519. return (ctx.body = yapi.commons.resReturn(null, 400, '项目id不能为空'));
  520. }
  521. let project = await this.projectModel.getBaseInfo(project_id);
  522. if (!project) {
  523. return (ctx.body = yapi.commons.resReturn(null, 406, '不存在的项目'));
  524. }
  525. if (project.project_type === 'private') {
  526. if ((await this.checkAuth(project._id, 'project', 'view')) !== true) {
  527. return (ctx.body = yapi.commons.resReturn(null, 406, '没有权限'));
  528. }
  529. }
  530. try {
  531. let result = await this.catModel.list(project_id),
  532. newResult = [];
  533. for (let i = 0, item, list; i < result.length; i++) {
  534. item = result[i].toObject();
  535. list = await this.Model.listByCatid(item._id);
  536. for (let j = 0; j < list.length; j++) {
  537. list[j] = list[j].toObject();
  538. }
  539. item.list = list;
  540. newResult[i] = item;
  541. }
  542. ctx.body = yapi.commons.resReturn(newResult);
  543. } catch (err) {
  544. ctx.body = yapi.commons.resReturn(null, 402, err.message);
  545. }
  546. }
  547. /**
  548. * 编辑接口
  549. * @interface /interface/up
  550. * @method POST
  551. * @category interface
  552. * @foldnumber 10
  553. * @param {Number} id 接口id,不能为空
  554. * @param {String} [path] 接口请求路径
  555. * @param {String} [method] 请求方式
  556. * @param {Array} [req_headers] 请求的header信息
  557. * @param {String} [req_headers[].name] 请求的header信息名
  558. * @param {String} [req_headers[].value] 请求的header信息值
  559. * @param {Boolean} [req_headers[].required] 是否是必须,默认为否
  560. * @param {String} [req_headers[].desc] header描述
  561. * @param {String} [req_body_type] 请求参数方式,有["form", "json", "text", "xml"]四种
  562. * @param {Mixed} [req_body_form] 请求参数,如果请求方式是form,参数是Array数组,其他格式请求参数是字符串
  563. * @param {String} [req_body_form[].name] 请求参数名
  564. * @param {String} [req_body_form[].value] 请求参数值,可填写生成规则(mock)。如@email,随机生成一条email
  565. * @param {String} [req_body_form[].type] 请求参数类型,有["text", "file"]两种
  566. * @param {String} [req_body_other] 非form类型的请求参数可保存到此字段
  567. * @param {String} [res_body_type] 相应信息的数据格式,有["json", "text", "xml"]三种
  568. * @param {String} [res_body] 响应信息,可填写任意字符串,如果res_body_type是json,则会调用mock功能
  569. * @param {String} [desc] 接口描述
  570. * @returns {Object}
  571. * @example ./api/interface/up.json
  572. */
  573. async up(ctx) {
  574. let params = ctx.params;
  575. if (!_.isUndefined(params.method)) {
  576. params.method = params.method || 'GET';
  577. params.method = params.method.toUpperCase();
  578. }
  579. let id = params.id;
  580. params.message = params.message || '';
  581. params.message = params.message.replace(/\n/g, '<br>');
  582. // params.res_body_is_json_schema = _.isUndefined (params.res_body_is_json_schema) ? true : params.res_body_is_json_schema;
  583. // params.req_body_is_json_schema = _.isUndefined(params.req_body_is_json_schema) ? true : params.req_body_is_json_schema;
  584. handleHeaders(params)
  585. let interfaceData = await this.Model.get(id);
  586. if (!interfaceData) {
  587. return (ctx.body = yapi.commons.resReturn(null, 400, '不存在的接口'));
  588. }
  589. if (!this.$tokenAuth) {
  590. let auth = await this.checkAuth(interfaceData.project_id, 'project', 'edit');
  591. if (!auth) {
  592. return (ctx.body = yapi.commons.resReturn(null, 400, '没有权限'));
  593. }
  594. }
  595. let data = Object.assign(
  596. {
  597. up_time: yapi.commons.time()
  598. },
  599. params
  600. );
  601. if (params.path) {
  602. let http_path;
  603. http_path = url.parse(params.path, true);
  604. if (!yapi.commons.verifyPath(http_path.pathname)) {
  605. return (ctx.body = yapi.commons.resReturn(
  606. null,
  607. 400,
  608. 'path第一位必需为 /, 只允许由 字母数字-/_:.! 组成'
  609. ));
  610. }
  611. params.query_path = {};
  612. params.query_path.path = http_path.pathname;
  613. params.query_path.params = [];
  614. Object.keys(http_path.query).forEach(item => {
  615. params.query_path.params.push({
  616. name: item,
  617. value: http_path.query[item]
  618. });
  619. });
  620. data.query_path = params.query_path;
  621. }
  622. if (
  623. params.path &&
  624. (params.path !== interfaceData.path || params.method !== interfaceData.method)
  625. ) {
  626. let checkRepeat = await this.Model.checkRepeat(
  627. interfaceData.project_id,
  628. params.path,
  629. params.method
  630. );
  631. if (checkRepeat > 0) {
  632. return (ctx.body = yapi.commons.resReturn(
  633. null,
  634. 401,
  635. '已存在的接口:' + params.path + '[' + params.method + ']'
  636. ));
  637. }
  638. }
  639. if (!_.isUndefined(data.req_params)) {
  640. if (Array.isArray(data.req_params) && data.req_params.length > 0) {
  641. data.type = 'var';
  642. } else {
  643. data.type = 'static';
  644. data.req_params = [];
  645. }
  646. }
  647. let result = await this.Model.up(id, data);
  648. let username = this.getUsername();
  649. let CurrentInterfaceData = await this.Model.get(id);
  650. let logData = {
  651. interface_id: id,
  652. cat_id: data.catid,
  653. current: CurrentInterfaceData.toObject(),
  654. old: interfaceData.toObject()
  655. };
  656. this.catModel.get(interfaceData.catid).then(cate => {
  657. let diffView2 = showDiffMsg(jsondiffpatch, formattersHtml, logData);
  658. if (diffView2.length <= 0) {
  659. return; // 没有变化时,不写日志
  660. }
  661. yapi.commons.saveLog({
  662. content: `<a href="/user/profile/${this.getUid()}">${username}</a>
  663. 更新了分类 <a href="/project/${cate.project_id}/interface/api/cat_${
  664. data.catid
  665. }">${cate.name}</a>
  666. 下的接口 <a href="/project/${cate.project_id}/interface/api/${id}">${
  667. interfaceData.title
  668. }</a><p>${params.message}</p>`,
  669. type: 'project',
  670. uid: this.getUid(),
  671. username: username,
  672. typeid: cate.project_id,
  673. data: logData
  674. });
  675. });
  676. this.projectModel.up(interfaceData.project_id, { up_time: new Date().getTime() }).then();
  677. if (params.switch_notice === true) {
  678. let diffView = showDiffMsg(jsondiffpatch, formattersHtml, logData);
  679. let annotatedCss = fs.readFileSync(
  680. path.resolve(
  681. yapi.WEBROOT,
  682. 'node_modules/jsondiffpatch/dist/formatters-styles/annotated.css'
  683. ),
  684. 'utf8'
  685. );
  686. let htmlCss = fs.readFileSync(
  687. path.resolve(yapi.WEBROOT, 'node_modules/jsondiffpatch/dist/formatters-styles/html.css'),
  688. 'utf8'
  689. );
  690. let project = await this.projectModel.getBaseInfo(interfaceData.project_id);
  691. let interfaceUrl = `${ctx.request.origin}/project/${
  692. interfaceData.project_id
  693. }/interface/api/${id}`;
  694. yapi.commons.sendNotice(interfaceData.project_id, {
  695. title: `${username} 更新了接口`,
  696. content: `<html>
  697. <head>
  698. <style>
  699. ${annotatedCss}
  700. ${htmlCss}
  701. </style>
  702. </head>
  703. <body>
  704. <div><h3>${username}更新了接口(${data.title})</h3>
  705. <p>项目名:${project.name} </p>
  706. <p>修改用户: ${username}</p>
  707. <p>接口名: <a href="${interfaceUrl}">${data.title}</a></p>
  708. <p>接口路径: [${data.method}]${data.path}</p>
  709. <p>详细改动日志: ${this.diffHTML(diffView)}</p></div>
  710. </body>
  711. </html>`
  712. });
  713. }
  714. yapi.emitHook('interface_update', id).then();
  715. ctx.body = yapi.commons.resReturn(result);
  716. return 1;
  717. }
  718. diffHTML(html) {
  719. if (html.length === 0) {
  720. return `<span style="color: #555">没有改动,该操作未改动Api数据</span>`;
  721. }
  722. return html.map(item => {
  723. return `<div>
  724. <h4 class="title">${item.title}</h4>
  725. <div>${item.content}</div>
  726. </div>`;
  727. });
  728. }
  729. /**
  730. * 删除接口
  731. * @interface /interface/del
  732. * @method GET
  733. * @category interface
  734. * @foldnumber 10
  735. * @param {Number} id 接口id,不能为空
  736. * @returns {Object}
  737. * @example ./api/interface/del.json
  738. */
  739. async del(ctx) {
  740. try {
  741. let id = ctx.request.body.id;
  742. if (!id) {
  743. return (ctx.body = yapi.commons.resReturn(null, 400, '接口id不能为空'));
  744. }
  745. let data = await this.Model.get(id);
  746. if (data.uid != this.getUid()) {
  747. let auth = await this.checkAuth(data.project_id, 'project', 'danger');
  748. if (!auth) {
  749. return (ctx.body = yapi.commons.resReturn(null, 400, '没有权限'));
  750. }
  751. }
  752. // let inter = await this.Model.get(id);
  753. let result = await this.Model.del(id);
  754. yapi.emitHook('interface_del', id).then();
  755. await this.caseModel.delByInterfaceId(id);
  756. let username = this.getUsername();
  757. this.catModel.get(data.catid).then(cate => {
  758. yapi.commons.saveLog({
  759. content: `<a href="/user/profile/${this.getUid()}">${username}</a> 删除了分类 <a href="/project/${
  760. cate.project_id
  761. }/interface/api/cat_${data.catid}">${cate.name}</a> 下的接口 "${data.title}"`,
  762. type: 'project',
  763. uid: this.getUid(),
  764. username: username,
  765. typeid: cate.project_id
  766. });
  767. });
  768. this.projectModel.up(data.project_id, { up_time: new Date().getTime() }).then();
  769. ctx.body = yapi.commons.resReturn(result);
  770. } catch (err) {
  771. ctx.body = yapi.commons.resReturn(null, 402, err.message);
  772. }
  773. }
  774. // 处理编辑冲突
  775. async solveConflict(ctx) {
  776. try {
  777. let id = parseInt(ctx.query.id, 10),
  778. result,
  779. userInst,
  780. userinfo,
  781. data;
  782. if (!id) {
  783. return ctx.websocket.send('id 参数有误');
  784. }
  785. result = await this.Model.get(id);
  786. if (result.edit_uid !== 0 && result.edit_uid !== this.getUid()) {
  787. userInst = yapi.getInst(userModel);
  788. userinfo = await userInst.findById(result.edit_uid);
  789. data = {
  790. errno: result.edit_uid,
  791. data: { uid: result.edit_uid, username: userinfo.username }
  792. };
  793. } else {
  794. this.Model.upEditUid(id, this.getUid()).then();
  795. data = {
  796. errno: 0,
  797. data: result
  798. };
  799. }
  800. ctx.websocket.send(JSON.stringify(data));
  801. ctx.websocket.on('close', () => {
  802. this.Model.upEditUid(id, 0).then();
  803. });
  804. } catch (err) {
  805. yapi.commons.log(err, 'error');
  806. }
  807. }
  808. async addCat(ctx) {
  809. try {
  810. let params = ctx.request.body;
  811. params = yapi.commons.handleParams(params, {
  812. name: 'string',
  813. project_id: 'number',
  814. desc: 'string'
  815. });
  816. if (!params.project_id) {
  817. return (ctx.body = yapi.commons.resReturn(null, 400, '项目id不能为空'));
  818. }
  819. if (!this.$tokenAuth) {
  820. let auth = await this.checkAuth(params.project_id, 'project', 'edit');
  821. if (!auth) {
  822. return (ctx.body = yapi.commons.resReturn(null, 400, '没有权限'));
  823. }
  824. }
  825. if (!params.name) {
  826. return (ctx.body = yapi.commons.resReturn(null, 400, '名称不能为空'));
  827. }
  828. let result = await this.catModel.save({
  829. name: params.name,
  830. project_id: params.project_id,
  831. desc: params.desc,
  832. uid: this.getUid(),
  833. add_time: yapi.commons.time(),
  834. up_time: yapi.commons.time()
  835. });
  836. let username = this.getUsername();
  837. yapi.commons.saveLog({
  838. content: `<a href="/user/profile/${this.getUid()}">${username}</a> 添加了分类 <a href="/project/${
  839. params.project_id
  840. }/interface/api/cat_${result._id}">${params.name}</a>`,
  841. type: 'project',
  842. uid: this.getUid(),
  843. username: username,
  844. typeid: params.project_id
  845. });
  846. ctx.body = yapi.commons.resReturn(result);
  847. } catch (e) {
  848. ctx.body = yapi.commons.resReturn(null, 402, e.message);
  849. }
  850. }
  851. async upCat(ctx) {
  852. try {
  853. let params = ctx.request.body;
  854. let username = this.getUsername();
  855. let cate = await this.catModel.get(params.catid);
  856. let auth = await this.checkAuth(cate.project_id, 'project', 'edit');
  857. if (!auth) {
  858. return (ctx.body = yapi.commons.resReturn(null, 400, '没有权限'));
  859. }
  860. let result = await this.catModel.up(params.catid, {
  861. name: params.name,
  862. desc: params.desc,
  863. up_time: yapi.commons.time()
  864. });
  865. yapi.commons.saveLog({
  866. content: `<a href="/user/profile/${this.getUid()}">${username}</a> 更新了分类 <a href="/project/${
  867. cate.project_id
  868. }/interface/api/cat_${params.catid}">${cate.name}</a>`,
  869. type: 'project',
  870. uid: this.getUid(),
  871. username: username,
  872. typeid: cate.project_id
  873. });
  874. ctx.body = yapi.commons.resReturn(result);
  875. } catch (e) {
  876. ctx.body = yapi.commons.resReturn(null, 400, e.message);
  877. }
  878. }
  879. async delCat(ctx) {
  880. try {
  881. let id = ctx.request.body.catid;
  882. let catData = await this.catModel.get(id);
  883. if (!catData) {
  884. ctx.body = yapi.commons.resReturn(null, 400, '不存在的分类');
  885. }
  886. if (catData.uid !== this.getUid()) {
  887. let auth = await this.checkAuth(catData.project_id, 'project', 'danger');
  888. if (!auth) {
  889. return (ctx.body = yapi.commons.resReturn(null, 400, '没有权限'));
  890. }
  891. }
  892. let username = this.getUsername();
  893. yapi.commons.saveLog({
  894. content: `<a href="/user/profile/${this.getUid()}">${username}</a> 删除了分类 "${
  895. catData.name
  896. }" 及该分类下的接口`,
  897. type: 'project',
  898. uid: this.getUid(),
  899. username: username,
  900. typeid: catData.project_id
  901. });
  902. let interfaceData = await this.Model.listByCatid(id);
  903. interfaceData.forEach(async item => {
  904. try {
  905. yapi.emitHook('interface_del', item._id).then();
  906. await this.caseModel.delByInterfaceId(item._id);
  907. } catch (e) {
  908. yapi.commons.log(e.message, 'error');
  909. }
  910. });
  911. await this.catModel.del(id);
  912. let r = await this.Model.delByCatid(id);
  913. return (ctx.body = yapi.commons.resReturn(r));
  914. } catch (e) {
  915. yapi.commons.resReturn(null, 400, e.message);
  916. }
  917. }
  918. /**
  919. * 获取分类列表
  920. * @interface /interface/getCatMenu
  921. * @method GET
  922. * @category interface
  923. * @foldnumber 10
  924. * @param {Number} project_id 项目id,不能为空
  925. * @returns {Object}
  926. * @example ./api/interface/getCatMenu
  927. */
  928. async getCatMenu(ctx) {
  929. let project_id = ctx.params.project_id;
  930. if (!project_id || isNaN(project_id)) {
  931. return (ctx.body = yapi.commons.resReturn(null, 400, '项目id不能为空'));
  932. }
  933. try {
  934. let project = await this.projectModel.getBaseInfo(project_id);
  935. if (project.project_type === 'private') {
  936. if ((await this.checkAuth(project._id, 'project', 'edit')) !== true) {
  937. return (ctx.body = yapi.commons.resReturn(null, 406, '没有权限'));
  938. }
  939. }
  940. let res = await this.catModel.list(project_id);
  941. return (ctx.body = yapi.commons.resReturn(res));
  942. } catch (e) {
  943. yapi.commons.resReturn(null, 400, e.message);
  944. }
  945. }
  946. /**
  947. * 获取自定义接口字段数据
  948. * @interface /interface/get_custom_field
  949. * @method GET
  950. * @category interface
  951. * @foldnumber 10
  952. * @param {String} app_code = '111'
  953. * @returns {Object}
  954. *
  955. */
  956. async getCustomField(ctx) {
  957. let params = ctx.request.query;
  958. if (Object.keys(params).length !== 1) {
  959. return (ctx.body = yapi.commons.resReturn(null, 400, '参数数量错误'));
  960. }
  961. let customFieldName = Object.keys(params)[0];
  962. let customFieldValue = params[customFieldName];
  963. try {
  964. // 查找有customFieldName的分组(group)
  965. let groups = await this.groupModel.getcustomFieldName(customFieldName);
  966. if (groups.length === 0) {
  967. return (ctx.body = yapi.commons.resReturn(null, 404, '没有找到对应自定义接口'));
  968. }
  969. // 在每个分组(group)下查找对应project的id值
  970. let interfaces = [];
  971. for (let i = 0; i < groups.length; i++) {
  972. let projects = await this.projectModel.list(groups[i]._id);
  973. // 在每个项目(project)中查找interface下的custom_field_value
  974. for (let j = 0; j < projects.length; j++) {
  975. let data = {};
  976. let inter = await this.Model.getcustomFieldValue(projects[j]._id, customFieldValue);
  977. if (inter.length > 0) {
  978. data.project_name = projects[j].name;
  979. data.project_id = projects[j]._id;
  980. inter = inter.map((item, i) => {
  981. item = inter[i] = inter[i].toObject();
  982. item.res_body = yapi.commons.json_parse(item.res_body);
  983. item.req_body_other = yapi.commons.json_parse(item.req_body_other);
  984. return item;
  985. });
  986. data.list = inter;
  987. interfaces.push(data);
  988. }
  989. }
  990. }
  991. return (ctx.body = yapi.commons.resReturn(interfaces));
  992. } catch (e) {
  993. yapi.commons.resReturn(null, 400, e.message);
  994. }
  995. }
  996. requiredSort(params) {
  997. return params.sort((item1, item2) => {
  998. return item2.required - item1.required;
  999. });
  1000. }
  1001. /**
  1002. * 更新多个接口case index
  1003. * @interface /interface/up_index
  1004. * @method POST
  1005. * @category col
  1006. * @foldnumber 10
  1007. * @param {Array} [id, index]
  1008. * @returns {Object}
  1009. * @example
  1010. */
  1011. async upIndex(ctx) {
  1012. try {
  1013. let params = ctx.request.body;
  1014. if (!params || !Array.isArray(params)) {
  1015. ctx.body = yapi.commons.resReturn(null, 400, '请求参数必须是数组');
  1016. }
  1017. params.forEach(item => {
  1018. if (item.id) {
  1019. this.Model.upIndex(item.id, item.index).then(
  1020. res => {},
  1021. err => {
  1022. yapi.commons.log(err.message, 'error');
  1023. }
  1024. );
  1025. }
  1026. });
  1027. return (ctx.body = yapi.commons.resReturn('成功!'));
  1028. } catch (e) {
  1029. ctx.body = yapi.commons.resReturn(null, 400, e.message);
  1030. }
  1031. }
  1032. /**
  1033. * 更新多个接口cat index
  1034. * @interface /interface/up_cat_index
  1035. * @method POST
  1036. * @category col
  1037. * @foldnumber 10
  1038. * @param {Array} [id, index]
  1039. * @returns {Object}
  1040. * @example
  1041. */
  1042. async upCatIndex(ctx) {
  1043. try {
  1044. let params = ctx.request.body;
  1045. if (!params || !Array.isArray(params)) {
  1046. ctx.body = yapi.commons.resReturn(null, 400, '请求参数必须是数组');
  1047. }
  1048. params.forEach(item => {
  1049. if (item.id) {
  1050. this.catModel.upCatIndex(item.id, item.index).then(
  1051. res => {},
  1052. err => {
  1053. yapi.commons.log(err.message, 'error');
  1054. }
  1055. );
  1056. }
  1057. });
  1058. return (ctx.body = yapi.commons.resReturn('成功!'));
  1059. } catch (e) {
  1060. ctx.body = yapi.commons.resReturn(null, 400, e.message);
  1061. }
  1062. }
  1063. async schema2json(ctx) {
  1064. let schema = ctx.request.body.schema;
  1065. let required = ctx.request.body.required;
  1066. let res = yapi.commons.schemaToJson(schema, {
  1067. alwaysFakeOptionals: _.isUndefined(required) ? true : require
  1068. });
  1069. // console.log('res',res)
  1070. return (ctx.body = res);
  1071. }
  1072. // 获取开放接口数据
  1073. async listByOpen(ctx) {
  1074. let project_id = ctx.request.query.project_id;
  1075. if (!project_id) {
  1076. return (ctx.body = yapi.commons.resReturn(null, 400, '项目id不能为空'));
  1077. }
  1078. let project = await this.projectModel.getBaseInfo(project_id);
  1079. if (!project) {
  1080. return (ctx.body = yapi.commons.resReturn(null, 406, '不存在的项目'));
  1081. }
  1082. if (project.project_type === 'private') {
  1083. if ((await this.checkAuth(project._id, 'project', 'view')) !== true) {
  1084. return (ctx.body = yapi.commons.resReturn(null, 406, '没有权限'));
  1085. }
  1086. }
  1087. let basepath = project.basepath;
  1088. try {
  1089. let result = await this.catModel.list(project_id),
  1090. newResult = [];
  1091. for (let i = 0, item, list; i < result.length; i++) {
  1092. item = result[i].toObject();
  1093. list = await this.Model.listByInterStatus(item._id, 'open');
  1094. for (let j = 0; j < list.length; j++) {
  1095. list[j] = list[j].toObject();
  1096. list[j].basepath = basepath;
  1097. }
  1098. newResult = [].concat(newResult, list);
  1099. }
  1100. ctx.body = yapi.commons.resReturn(newResult);
  1101. } catch (err) {
  1102. ctx.body = yapi.commons.resReturn(null, 402, err.message);
  1103. }
  1104. }
  1105. }
  1106. module.exports = interfaceController;