koa路由自动注册

安装
pnpm install require-directory
路由加载
static initRouters() {
    // 绝对路径
    const apiDir = `${process.cwd()}/router`;

    // 自动加载路由
    requireDirectory(module, apiDir, {
      visit: whenLoadModule
    });

    // 判断加载模块是否是路由
    function whenLoadModule(obj) {
      if (obj instanceof Router) {
        /**
         * 用中间件启动路由
         * router.routes() 启动路由
         * router.allowedMethods() 允许任何请求
         */
        InitManager.app.use(obj.routes(), obj.allowedMethods());
      }
    }
  }
posted @ 2023-08-31 16:15  不随。  阅读(12)  评论(0编辑  收藏  举报  来源