The NestJS documentation says to serve static files like this:
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ServeStaticModule } from '@nestjs/serve-static';
import { join } from 'path';
@Module({
imports: [
ServeStaticModule.forRoot({
rootPath: join(__dirname, '..', 'client'),
}),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
But as a DI and SOLID practitioner, I want to make the rootPath configurable. Lets say I have a ConfigModule
or my own ConstantsModule
. How do I inject rootPath
in a way similar to this?
@Module({
imports: [
ServeStaticModule.forRoot({
rootPath: this.configService.get<string>('staticRootPath'),
}),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
The correct answer:
ServeStaticModule.forRootAsync({
inject: [ConfigService],
useFactory: (configService: ConfigService) => [{
rootPath: join(__dirname, '..', configService.get<string>('STATIC_FOLDER')),
}]
})
Even if it is not documented, you can use the forRootAsync
, it is typical for NestJS modules to have this version which allows you to inject dependencies and/or do async configuration:
@Module({
imports: [
ServeStaticModule.forRootAsync({
imports: [ConfigModule],
injects: [ConfigService],
useFactory: (configService) => ({
rootPath: configService.get<string>('staticRootPath')
})
}),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
For reference, found it in the GitHub sources
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With