Sobes.tech
Middle — Middle+

How is the principle of polymorphism implemented in the NestJS framework and how is it used to extend functionality?

sobes.tech AI

Answer from AI

In NestJS, the principle of polymorphism is implemented through the use of abstractions, interfaces, and dependency injection. This allows creating extendable and replaceable components.

For example, you can define a common interface or abstract class for a service, and then implement several specific versions of this service. Depending on the configuration or context, NestJS will inject the required implementation.

This is used to extend functionality when you need to replace or augment behavior without changing existing code. Polymorphism also manifests in the use of decorators and middleware, which can handle different types of data or requests uniformly.

Example:

// Interface
export interface PaymentService {
  pay(amount: number): Promise<boolean>;
}

// Implementation for PayPal
@Injectable()
export class PaypalService implements PaymentService {
  async pay(amount: number) {
    // PayPal payment logic
    return true;
  }
}

// Implementation for Stripe
@Injectable()
export class StripeService implements PaymentService {
  async pay(amount: number) {
    // Stripe payment logic
    return true;
  }
}

// In the module, you can choose which implementation to use
@Module({
  providers: [
    {
      provide: PaymentService,
      useClass: PaypalService, // or StripeService
    },
  ],
})
export class PaymentModule {}

Thus, NestJS allows easily extending and replacing functionality through polymorphism and DI.

How is the principle of polymorphism implemented in… - sobes.tech