NestJS中使用DynamicModule实现模块动态加载

2024-12-21  本文已影响0人  kongxx

1. 介绍

在NestJS中,模块是组织代码的基本单元,它将相关的服务和控制器组织在一起。然而,在某些情况下,我们可能需要根据不同的条件动态加载模块,以满足不同的业务需求。这时,就可以使用DynamicModule了。

DynamicModule是NestJS提供的一种动态加载模块的方式,它允许我们在运行时动态地加载模块,看下面的例子。

2. 首先创建一个模块,比如这里的 config service和module

config.service.ts

import { Injectable, Inject } from '@nestjs/common';
import * as fs from 'fs';

@Injectable()
export class ConfigService {
  constructor(@Inject('CONFIG_OPTIONS') private options: any) {
    // TODO load config from options
    console.log('load config from ', options.folder);
  }

  get(key: string): string {
    // TODO get config
    console.log('get config value ...');
    return 'hello world';
  }
}

config.module.ts

import { DynamicModule, Module } from '@nestjs/common';
import { ConfigService } from './config.service';

@Module({})
export class ConfigModule {
  static register(options: any): DynamicModule {
    return {
      module: ConfigModule,
      providers: [
        {
          provide: 'CONFIG_OPTIONS',
          useValue: options,
        },
        ConfigService,
      ],
      exports: [ConfigService],
    };
  }
}

3. 在主模块中导入动态模块

app.module.ts

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ConfigModule } from './plugins/config/config.module';
import * as path from 'path';

@Module({
  imports: [ConfigModule.register({ folder: './config' })],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

4. 在控制器中使用动态模块服务

app.controller.ts

import { Controller, Get, Inject } from '@nestjs/common';
import { AppService } from './app.service';
import { ConfigService } from './plugins/config/config.service';

@Controller()
export class AppController {
  constructor(
    private readonly appService: AppService,
    @Inject(ConfigService)
    private readonly configService: ConfigService,
  ) {}

  @Get()
  async getHello() {
    console.log(this.configService.get('key'));

    return this.appService.getHello();
  }
}
上一篇 下一篇

猜你喜欢

热点阅读