eps.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. import { cloneDeep, merge } from 'lodash-es';
  2. import { BaseService, service } from '../service';
  3. import type { Module } from '../types';
  4. import { path2Obj } from '../utils';
  5. import { config, isDev } from '/@/config';
  6. import { eps } from 'virtual:eps';
  7. import { hmr } from '../hooks';
  8. import { module } from '../module';
  9. // 更新事件
  10. function onUpdate() {
  11. // 设置 request 方法
  12. function set(d: any) {
  13. if (d.namespace) {
  14. const a = new BaseService(d.namespace);
  15. for (const i in d) {
  16. const { path, method = 'get' } = d[i];
  17. if (path) {
  18. a.request = a.request;
  19. // @ts-ignore
  20. a[i] = function (data?: any) {
  21. return this.request({
  22. url: path,
  23. method,
  24. [method.toLocaleLowerCase() == 'post' ? 'data' : 'params']: data
  25. });
  26. };
  27. }
  28. }
  29. for (const i in a) {
  30. // @ts-ignore
  31. d[i] = a[i];
  32. }
  33. } else {
  34. for (const i in d) {
  35. set(d[i]);
  36. }
  37. }
  38. }
  39. // 遍历每一个方法
  40. set(eps.service);
  41. // 合并 eps
  42. merge(service, eps.service);
  43. // 合并[local]
  44. merge(
  45. service,
  46. cloneDeep(
  47. path2Obj(
  48. module.list.reduce((a, b) => {
  49. return a.concat(...((b.services as any[]) || []));
  50. }, [])
  51. )
  52. )
  53. );
  54. // 热更新处理
  55. hmr.setData('service', service);
  56. // 提示
  57. if (isDev) {
  58. console.log('[cool-eps] updated');
  59. }
  60. }
  61. export function createEps(modules: Module[]) {
  62. // 更新 eps
  63. onUpdate();
  64. // 开发环境下,生成本地 service 的类型描述文件
  65. if (isDev && config.test.eps) {
  66. const list: any[] = [];
  67. // 模拟 eps 数据
  68. modules.forEach(m => {
  69. m.services?.forEach(s => {
  70. const api = Array.from(
  71. new Set([
  72. ...Object.getOwnPropertyNames(s.value.constructor.prototype),
  73. 'page',
  74. 'list',
  75. 'info',
  76. 'delete',
  77. 'update',
  78. 'add'
  79. ])
  80. )
  81. .filter(e => !['constructor', 'namespace'].includes(e))
  82. .map(e => {
  83. return {
  84. path: `/${e}`
  85. };
  86. });
  87. list.push({
  88. api,
  89. module: m.name,
  90. name: s.value.constructor.name + 'Entity',
  91. prefix: `/admin/${s.path}`,
  92. isLocal: true
  93. });
  94. });
  95. });
  96. // 生成文件
  97. service.request({
  98. url: '/__cool_eps',
  99. method: 'POST',
  100. proxy: false,
  101. data: {
  102. list
  103. }
  104. });
  105. }
  106. }
  107. // 监听 vite 触发事件
  108. if (import.meta.hot) {
  109. import.meta.hot.on('eps-update', ({ service }) => {
  110. if (service) {
  111. eps.service = service;
  112. }
  113. onUpdate();
  114. });
  115. }