Search code examples
nestjsnestjs-config

How to get config in controller route of NestJS?


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.

In the end, the route I want is: localhost/animal/cat/snowflake/meow.


Edit: I attempted it with a normal variable, and it works. Apparently the issue is with my implementation of NestJS's config package.


Solution

  • 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.