Home > Software engineering >  Inject list of interfaces to a class - NestJs
Inject list of interfaces to a class - NestJs

Time:08-08

Let's say I have this interface:

export interface IParser {
  parse(text: string):string
}

and a couple of classes implementing the interface:

@Injectable()
export class FirstParser implements IParser {
   public parse(text: string): string {
     return text   'first';
   }
}

@Injectable()
export class SecondParser implements IParser {
   public parse(text: string): string {
     return text   'second';
   }
}

Now, I have a service that I'm trying to inject to him list of parsers:

@Injectable()
export class ParserService {
    constructor(private readonly parsers: IParser[]) {}

    public parse(text: string): string {
        let parsedText = text;
        parsedText = this.parsers.reduce((acc: string, result) => {
            return result.parse(acc);
        }, parsedText);
        return parsedText;
    }
}

I'm trying to make the app module (in this case the parser-service.module.ts) to work by injecting array/list of the class including FirstParser, SecondParser.

@Module({
    providers: [
        ParserService,
        {
          provide: Array<IParser>,
          useClass: ???,
        },
    ],
})
export class ParserServiceModule {}

Any ideas? is it possible at all in NestJs?

Thanks.

CodePudding user response:

The functionality you are trying to achieve has already been requested as a feature but hasn't been implemented due to the low priority. Take a look at the feature request.

However, you could utilize the factory provider functionality by turning the IParser implementations into an array.


@Module({
    providers: [
        FirstParser,
        SecondParser,
        {
          provide: 'Parser',
          useFactory: (...parsers) => new ParserService(parsers),
          inject: [FirstParser, SecondParser],
        },
    ],
})
export class ParserServiceModule {}
  • Related