首页 > 解决方案 > 如何获取模块名称,哪个控制器处理请求?

问题描述

我想获取模块的名称,哪个控制器处理请求。

@Get('/')
getIndex() {
  console.log('name of module');
}

标签: nestjs

解决方案


我不知道你的问题背后的确切目的,但我会给你一些选择。

第一个更脏。您可以通过在 modules 容器中找到您的 productController 导入的模块实例来获取它。

import { Controller, Get, Query } from '@nestjs/common';
import { ModulesContainer } from '@nestjs/core';
import { Module } from '@nestjs/core/injector/module';

@Controller('path')
export class ProductController {
    constructor(
        private modulesContainer: ModulesContainer,
        private productService: ProductService
    ) { }


    @Get()
    findAll(@Query() dto: any) {
        let yourModule: Module; 
        this.modulesContainer.forEach((v) => {
            if(v.controllers.has(this.constructor.name)) { // in this condition, you will find your module based in the imports from it, if your controller is importe in some module it will get the module and put in "yourModule" variable.
                // Here
                yourModule= v;
            }
        });

        console.log(yourModule);
        return  this.productService.findAll();
    }

}

对于更清洁的方法,您可以在控制器中获取 moduleRef

import { Controller, Get, Query } from '@nestjs/common';
import { ModuleRef} from '@nestjs/core';

@Controller('path')
export class ProductController {
    constructor(
        private moduleRef: ModuleRef,
        private productService: ProductService
    ) { }


    @Get()
    findAll(@Query() dto: any) {
        console.log(this.moduleRef) //your module ref
        return  this.productService.findAll();
    }

}

但当然取决于你想要做什么。


推荐阅读