generateService.js 2.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import axios from "axios";
  2. import fs from 'fs';
  3. const swagger = 'http://127.0.0.1:9087/api/v2/api-docs';
  4. const outDir = './src/service/';
  5. const requestStr = "import request from '@/utils/request';";
  6. const commentTpl = (summary) => [
  7. '/*',
  8. ` * ${summary}`,
  9. ' */',
  10. ]
  11. const apiTpl = (name, method, path) => {
  12. const apiName = `${method}${name}`;
  13. const hasPathParams = path.indexOf('{') > -1;
  14. const apiDetail = `const ${apiName}ById = (id) => request(\`${path.replace('{', '${')}\`);`;
  15. const apiList = `const ${apiName} = (params) => request('${path}', { params });`;
  16. const apiSave = `const ${apiName} = (data) => request('${path}', { data, method: 'post' });`;
  17. const apiUpdate = `const ${apiName} = (id, data) => request(\`${path.replace('{', '${')}\`, { data, method: 'put' });`;
  18. const apiDelete = `const ${apiName} = (id) => request(\`${path.replace('{', '${')}\`, { method: 'delete' });`;
  19. switch(method) {
  20. case 'get':
  21. return hasPathParams ? apiDetail : apiList;
  22. case 'post':
  23. return apiSave;
  24. case 'put':
  25. return apiUpdate;
  26. case 'delete':
  27. return apiDelete;
  28. default:
  29. return '';
  30. }
  31. }
  32. axios.get(swagger).then((res) => {
  33. const { paths, tags } = res.data;
  34. const files = Object.keys(paths).reduce((acc, path) => {
  35. const allAPI = paths[path];
  36. const apiName = getApiName(path);
  37. Object.keys(allAPI).forEach((method) => {
  38. const api = allAPI[method];
  39. const fname = getFileName(api, tags);
  40. const f = acc[fname] || [requestStr, ''];
  41. const content = [
  42. ...commentTpl(api.summary),
  43. `export ${apiTpl(apiName, method, path)}`,
  44. '',
  45. ]
  46. acc[fname] = f.concat(content)
  47. }, []);
  48. return acc;
  49. }, {});
  50. // 写入文件
  51. Object.keys(files).forEach(f => {
  52. const fname = `${outDir}${f}.js`
  53. const content = files[f].join('\n');
  54. fs.writeFile(fname, content, err => {
  55. console.error(err);
  56. });
  57. });
  58. })
  59. function getFileName(api, tags) {
  60. const tagName = api.tags[0];
  61. const tag = tags.filter(x => x.name == tagName)[0];
  62. const descriptions = tag.description.split(' ');
  63. const fname = descriptions.filter(x => x != 'Controller');
  64. // 转为小写
  65. return fname.join('').toLowerCase();
  66. };
  67. function getApiName(path) {
  68. const parts = path.split('/').reverse();
  69. const part = parts[0].indexOf('{') > -1 ? parts[1] : parts[0];
  70. // 首字母大写, - 转驼峰
  71. return part.replace(/^./, m => m.toUpperCase())
  72. .replace(/\-./, m => (m.length > 1 ? m[1].toUpperCase() : m));
  73. }