请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

12-26 在这里写?

export function Controller(reqRootPath: string): MyClassDecorator {
  return function (targetClass): any {
    for (let methodname in targetClass.prototype) {
      // 就改了一下这句
      const routerpath = reqRootPath + Reflect.getMetadata("path", targetClass.prototype, methodname);
      const methodType: MethodType = Reflect.getMetadata("methodType", targetClass.prototype, methodname)
      const targetMethodfunc: RequestHandler = targetClass.prototype[methodname];
      const middleawres: RequestHandler[] = Reflect.getMetadata("middleawares", targetClass.prototype, methodname) || []
      
      if (routerpath && methodType) {
        router[methodType](routerpath, ...[...middleawres, targetMethodfunc])
      }
    }
  }
}

正在回答 回答被采纳积分+3

1回答

keviny79 2023-08-16 22:02:58

各位同学:这个答案我公布了,路过同学看答案之前务必先思考后,实在想不出来了再来看,这样印象要深很多!

export function Controller(modulePath: string = '/') {

  // console.log('进入控制器装饰器....')

  function getFullPath(reqPath: string) {

    if (modulePath) {

      if (modulePath.length > 1) {

        if (!modulePath.startsWith('/')) {

          modulePath = `/${modulePath}`

        }

      } else if (modulePath === '/') {

        modulePath = ''

      }

    }

    return `${modulePath}${reqPath}`

  }

  return function (targetClass: { new (...args: any): any }) {

    //console.log('targetClass.prototype:', targetClass.prototype)

    // 1. 获取原型上的请求方法名

    Object.keys(targetClass.prototype).forEach((methodname) => {

      // 2. 根据方法名获取具体的方法体

      const routerHandlerFn = targetClass.prototype[methodname]

      // 3. 获取请求路径和请求类型,根路由对象

      const reqPath = Reflect.getMetadata('path', targetClass.prototype, methodname)

      const fullReqPath = getFullPath(reqPath)

      const reqMethodType: MethodType = Reflect.getMetadata('methodType', targetClass.prototype, methodname)

      // 4. 实现路由请求

      const rootRouter = AllCtrlRouterLoader.app.context.rootRouter

      if (fullReqPath && reqMethodType) {

        rootRouter[reqMethodType](fullReqPath, routerHandlerFn)

      }

    })

  }

}



0 回复 有任何疑惑可以回复我~
问题已解决,确定采纳
还有疑问,暂不采纳
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号