nestjs-extractor
TypeScript icon, indicating that this package has built-in type declarations

1.1.0 • Public • Published

Description

npm version install size

NestJS module for extract providers from parent non-global modules

Installation

npm install --save nestjs-extractor

Usage

Create ZooConfigService and ZooConfigModule

@Injectable()
class ZooConfigService {
    public get zooName(): string {
        return process.env.ZOO_NAME ?? 'Central Park Zoo';
    }
}

@Module({
    providers: [ZooConfigService],
    exports: [ZooConfigService],
})
class ZooConfigModule {}

Provide ZooConfigService through ExtractorModule in CatModule...

import { ExtractorModule } from 'nestjs-extractor';

@Module({
    imports: [ExtractorModule.forFeature([ZooConfigService])],
    providers: [CatService],
    controllers: [CatController],
})
class CatModule {}

...and use ZooConfigService in CatController...

@Controller()
class CatController {
    public constructor(
        private readonly catService: CatService,
        private readonly zooConfigService: ZooConfigService,
    ) {}

    @Get('/cat/:catId/info')
    public getCatInfo(
        @Param('catId', ParseIntPipe) catId: number,
    ): string {
        const catName = this.catService.getCatById(catId);
        const zooName = this.zooConfigService.zooName;

        return `Cat ${catName} from ${zooName}`;
    }
}

Import CatModule in ZooModule

@Module({
    imports: [CatModule, DogModule],
})
class ZooModule {}

Import ZooConfigModule and ZooModule in AppModule

@Module({
    imports: [ZooConfigModule, ZooModule],
})
class AppModule {}

Options

You can provide the options for the providers search as the second argument of the ExtractorModule.forFeature() function

type ExtractorModuleOptions = {
    optional?: boolean;
};
  1. optional is needed for providers marked as @Optional()
@Injectable()
class Service {
    public constructor(
        @Optional()
        public readonly nestedService: NestedService,
    ) {}
}

@Module({
    imports: [
        ExtractorModule.forFeature([NestedService], { optional: true }),
    ],

    providers: [Service],
})
class ServiceModule {}

License

MIT

Package Sidebar

Install

npm i nestjs-extractor

Weekly Downloads

331

Version

1.1.0

License

MIT

Unpacked Size

22.2 kB

Total Files

37

Last publish

Collaborators

  • yeswell