如何在 NestJS 的控制器路由中获取配置? [英] How to get config in controller route of NestJS?
问题描述
我试图让一个变量通过装饰器的控制器 prefix
和方法 path
参数出现.我知道 Nest Router,但我宁愿尽可能避免使用它.
I'm trying to get a variable to appear through both the controller prefix
and the method path
parameters of the decorators. I know of Nest Router, but I'd rather avoid using it while I can.
/*************************
* eneity.config.ts
*************************/
import { registerAs } from '@nestjs/config';
export default registerAs('cat', () => ({
cat: {
urlPrefix: 'cat',
paramName: 'meow',
}
})
);
/*************************
* cat.module.ts
*************************/
import entityConfig from 'config/entity.config';
import { CatController } from 'entities/cat/cat.controller';
import { ConfigModule, ConfigService } from '@nestjs/config';
@Module({
imports : [ConfigModule.forFeature(entityConfig),],
providers : [ConfigService],
controllers: [CatController],
})
export class CatModule {}
/*************************
* cat.controller.ts
*************************/
import { Controller, Request, Get } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
@Controller(`${this.urlPrefix}/cat`) // <<<<< Here
export class CatController {
private readonly urlPrefix;
private readonly paramName;
constructor(
private readonly configService: ConfigService,
) {
this.urlPrefix = this.configService.get<string>('cat.urlPrefix'); // animal
this.paramName = this.configService.get<string>('cat.paramName'); // meow
}
@Get(`snowflake/:${this.paramName}`) // <<<<< Here
getProfile(@Request() req) {
return 'meowww';
}
}
我尝试照原样执行,但它一直给我未定义",即使我将它记录到构造函数中的控制台时也会显示.我希望能够使用配置来设置这些常量.
I tried to do it as is, and it keeps giving me "undefined", even though it shows up if I log it to console in the constructor. I want to be able to use the configuration to set these constants.
最后我想要的路线是:localhost/animal/cat/snowflake/meow
.
In the end, the route I want is: localhost/animal/cat/snowflake/meow
.
我用一个普通变量尝试过,它有效.显然问题出在我对 NestJS 配置包的实现上.
I attempted it with a normal variable, and it works. Apparently the issue is with my implementation of NestJS's config package.
推荐答案
您的配置服务没有问题,而是装饰器在 Typescript/JavaScript 中的工作方式有问题.由于装饰器上下文的工作方式,装饰器无法访问类成员.如果您想让端点可配置,这首先看起来是个坏主意,您可以使用 nest-router 正如你提到的.
There's not an issue with your config service, but rather an issue with how decorators work in Typescript/JavaScript. Decorators cannot access class members, due to how the decorator context works. If you want to make the endpoint configurable, which seems like a bad idea in the first place, you can use nest-router as you mentioned.
这篇关于如何在 NestJS 的控制器路由中获取配置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!