nestjs - 如何获取模块名称,哪个控制器处理请求?
问题描述
我想获取模块的名称,哪个控制器处理请求。
@Get('/')
getIndex() {
console.log('name of module');
}
解决方案
我不知道你的问题背后的确切目的,但我会给你一些选择。
第一个更脏。您可以通过在 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();
}
}
但当然取决于你想要做什么。
推荐阅读
- types - Haxe:如何检查变量是否为函数
- html - 将样式应用于类而不影响导航 LI 中的其他类?
- javascript - 复选框上的 html5 验证
- swiftui - 在 init() 中初始化 2 个变量:在初始化所有存储的属性之前使用“self”
- javascript - 将 PDF 中的特定单词/数字保存到 Google 电子表格。(应用程序脚本)
- azure - 如何允许任何人通过 MsGraph 创建 Teams 会议
- c++ - 设置成员变量值后,该值在 getter 函数内部发生变化
- php - Laravel Eloquent 3 个表 + 1 个数据透视表
- websocket - 很多 tcp 窗口更新大小段
- python - 为什么它说左上角没有在函数pygame中定义?