Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject the path configuration into ServeStaticModule from another service?

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 {}
like image 885
JBCP Avatar asked Sep 03 '25 06:09

JBCP


2 Answers

The correct answer:

ServeStaticModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (configService: ConfigService) => [{
          rootPath: join(__dirname, '..', configService.get<string>('STATIC_FOLDER')),
      }]
})
like image 157
Aleksa Avatar answered Sep 05 '25 00:09

Aleksa


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

like image 28
leonardfactory Avatar answered Sep 05 '25 01:09

leonardfactory