What is the proper way of accessing the global ConfigService in any parts of the app, i.e. DTOs, some helper functions?
I have the config service which is using the object made of several .yml configs.
ConfigModule.forRoot({
// Merge YML config files into 1 config and validate it
load: [() => ({ ...appConfig, ...validationConfig })],
isGlobal: true,
validationSchema: configSchema,
}),
Then I'm using it where it's needed. It's quite simple to use in other services by adding it to the constructor:
// some simplified example of the service using the ConfigService
import { ConfigService } from '@nestjs/config'
@Injectable()
export class ImagesService {
private cloudAccountId: string
constructor(private readonly configService: ConfigService) {
this.cloudAccountId = this.configService.get<string('CLOUD_ACCOUNT_ID')
}
}
But I'm not sure how to use it correctly in places like: some helper functions (validators), controller decorators, DTOs. Especially assuming the context (but not only it, I'm not sure it's ok to just create another ConfigService instance for using in independent functions)
One of examples:
export class SomeController {
private maxFileSize: number
constructor(
private readonly configService: ConfigService
) {
this.maxFileSize = this.configService.get<number>('validation.max_file_size')
}
@Post('/some-endpoint')
@HttpCode(201)
@ApiConsumes('multipart/form-data')
@UseInterceptors(
FileInterceptor('file', {
limits: { fileSize: this.maxFileSize, files: 1 },
fileFilter: imageFilter,
}),
)
async uploadFile() {}
^ in this case this is possibly undefined, I believe because of the different context.
I couldn't find any real examples in docs.
You can't access class properties from within decorators, as they are not bound to the context of the class. What you can do instead is use the
MulterModule.registerAsync()and inject theConfigServiceto set up the multer options for that module.