DEV Community

ILshat Khamitov
ILshat Khamitov

Posted on

3 3

Use abstract-class for custom injecting logic for NestJS with multi providing

Installation

npm i --save nestjs-custom-injector
Enter fullscreen mode Exit fullscreen mode

Links

https://nestjs-custom-injector.site15.ru/api/#/abstract-class - Demo application with nestjs-custom-injector.
https://github.com/EndyKaufman/nestjs-custom-injector/tree/develop/apps/demo/src/app/abstract-class - Example.

Usage

Create abstract class in animal.provider.ts

export abstract class AbstractAnimalProvider {
  abstract type: string;
  abstract say(): string;
}

Enter fullscreen mode Exit fullscreen mode

Create first type of logic for cats in animal-cats.service.ts

import { Injectable } from '@nestjs/common';
import { AbstractAnimalProvider } from './animal.provider';

@Injectable()
export class AnimalCatsService extends AbstractAnimalProvider {
  type = 'cat';
  say(): string {
    return 'meow';
  }
}
Enter fullscreen mode Exit fullscreen mode

Create second type of logic for dogs in animal-dogs.service.ts

import { Injectable } from '@nestjs/common';
import { AbstractAnimalProvider } from './animal.provider';

@Injectable()
export class AnimalDogsService extends AbstractAnimalProvider {
  type = 'dog';
  say(): string {
    return 'woof';
  }
}
Enter fullscreen mode Exit fullscreen mode

Create controller animals.controller.ts

import { Controller, Get, Query } from '@nestjs/common';
import { CustomInject } from 'nestjs-custom-injector';
import { AbstractAnimalProvider } from './animal.provider';

@Controller('animals')
export class AnimalsController {
  @CustomInject(AbstractAnimalProvider, { multi: true })
  private animalProviders!: AbstractAnimalProvider[];

  @Get('animal-types')
  animalTypes() {
    return this.animalProviders.map((animalProvider) => animalProvider.type);
  }

  @Get('what-says-animals')
  whatSaysAnimals() {
    return this.animalProviders.map(
      (animal) => `${animal.type} say ${animal.say()}`
    );
  }

  @Get('who-say')
  whoSay(@Query('voice') voice: string) {
    const animal = this.animalProviders.find(
      (animal) => animal.say() === voice
    );
    if (!animal) {
      return { error: `I don't know who say ${voice}` };
    }
    return `${animal.type} say ${animal.say()}`;
  }
}
Enter fullscreen mode Exit fullscreen mode

Append all logic to main app module app.module.ts

import { Module } from '@nestjs/common';
import { CustomInjectorModule } from 'nestjs-custom-injector';
import { AnimalCatsService } from './animal-cats.service';
import { AnimalDogsService } from './animal-dogs.service';
import { AnimalsController } from './animals.controller';
import { AbstractAnimalProvider } from './animal.provider';

@Module({
  ...
  imports: [
    ...
    CustomInjectorModule.forRoot(),
    CustomInjectorModule.forFeature({
      providers: [{ provide: AbstractAnimalProvider, useClass: AnimalCatsService }],
    }),
    CustomInjectorModule.forFeature({
      providers: [
        { provide: AbstractAnimalProvider, useValue: new AnimalDogsService() },
      ],
    }),
    ...
  ],
  controllers: [
    ...
    AnimalsController
    ...
  ]
  ...
})
export class AppModule {}
Enter fullscreen mode Exit fullscreen mode

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more