cool-team-official / cool-admin-midway

🔥 cool-admin(midway版)一个很酷的后台权限管理框架,Ai编码、流程编排、模块化、插件化、CRUD极速开发,永久开源免费,基于midway.js 3.x、typescript、typeorm、mysql、jwt、vue3、vite、element-ui等构建
https://cool-js.com
MIT License
2.65k stars 588 forks source link

CoolRpcService装饰器下的insertParam不生效 #84

Open nobu121 opened 2 years ago

nobu121 commented 2 years ago

rpc模块下的CoolRpcService装饰器下的insertParam方法不生效 检查了下源码 insertParam函数并没有调用

以下是我的临时解决方案

在主服务新增中间件,将需要使用的ctx内容和 request参数一起传到 微服务

middleware

/**
 * 基础api转发
 */
@Middleware()
export class ApiMiddleware implements IMiddleware<Context, NextFunction> {
  @Inject()
  rpc: CoolRpc;

  resolve() {
    return async (ctx: Context, next: NextFunction) => {
      // 控制器前执行的逻辑
      const startTime = Date.now();

      const apiDesc = ['add', 'update', 'info', 'delete', 'list', 'page'];

      let { url, body, query, method } = ctx.request;

      let data;

      if (method == 'GET') {
        url = url.split('?')[0];
        data = JSON.parse(JSON.stringify(query));
      } else {
        data = body;
      }

      // 传递管理员信息到微服务
      if (ctx.admin) {
        data.admin = ctx.admin;
      }

      const urls = url.split('/');
      const api = urls.at(-1);

      // 默认接口
      if (apiDesc.includes(api)) {
        const module = urls.at(-2);

        const allServices: any[] = await this.rpc.broker.call('$node.services');
        const isExist = allServices.some(serve => serve.name == module);

        if (!isExist) {
          await next();
          return;
        }

        // 服务名构建
        const service = urls[1] + _.capitalize(module) + 'Service';

        // 转发请求
        ctx.request.method = 'POST';
        ctx.request.url = '/_rpc/gatway';
        ctx.request.body = {
          name: module,
          service,
          method: api,
          params: data,
        };

        await next();
        // 控制器之后执行的逻辑
        console.log((Date.now() - startTime) + 'ms');
        return;
      } else {
        await next();
        return;
      }
    };
  }
}

rpc/service/base.ts

  // 新增前插入
  async insertParam(curdOption, params) {
    if (curdOption?.insertParam) {
      params = {
        ...params,
        ...(await curdOption.insertParam(params)),
      };
    }
    return params;
  }

...

  /**
   * 新增
   * @param param 数据
   */
  async add(params: any): Promise<Object> {
    if (!this.entity) throw new CoolValidateException(ERRINFO.NOENTITY);
    params = await this.insertParam(this.curdOption, params);
    await this.addOrUpdate(params);
    await this.modifyAfter(params);
    return {
      id: params.id,
    };
  }