What is a Provider

Providers in NestJS

A provider is anything NestJS can create and inject: services, repositories, factories, helpers, config values. Most providers are classes marked with @Injectable().

  • You register a provider in a module's providers array.
  • NestJS creates it once (singleton by default).
  • Any class that needs it asks for it in its constructor; NestJS passes the instance.

This is called Inversion of Control (IoC): your class does not call new ProductsService(). The framework does.

A Simple Service

src/products/pricing.service.ts

import { Injectable } from '@nestjs/common';

@Injectable()
export class PricingService {
  private readonly gstRate = 0.18;

  withGst(price: number): number {
    return Math.round(price * (1 + this.gstRate));
  }

  discounted(price: number, percent: number): number {
    return Math.round(price * (1 - percent / 100));
  }
}

Example

Business logic in a service is plain TypeScript, so you can try it without NestJS:

class PricingService {
  private readonly gstRate = 0.18;
  withGst(price: number): number {
    return Math.round(price * (1 + this.gstRate));
  }
  discounted(price: number, percent: number): number {
    return Math.round(price * (1 - percent / 100));
  }
}

const pricing = new PricingService();
console.log('MRP 1299 + GST =', pricing.withGst(1299));
console.log('20% off 2999 =', pricing.discounted(2999, 20));
console.log('20% off then GST =', pricing.withGst(pricing.discounted(2999, 20)));

Output

MRP 1299 + GST = 1533
20% off 2999 = 2399
20% off then GST = 2831