DEV Community

Cover image for NestJS - Providers
Ilya R
Ilya R

Posted on

3 1

NestJS - Providers

In the MVP in additional View and Controller, there are also Model. Model contain main and additional logic, and also contain logic for working with DB and third-party APIs. In NestJS, this function is assigned to Providers.

Providers in NestJS are registered in Modules they belong to. And also can be exported from the Module to be available in other parts of the application.

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

import { ProductsService } from './products.service';
import { ProductsController } from './products.controller';

@Module({
  controllers: [ProductsController],
  providers: [ProductsService],
})
export class ProductsModule {}
Enter fullscreen mode Exit fullscreen mode

One of the features of a provider is that the provider is injected, for example, into the controller's constructor for further application work.

import { Controller, Get } from '@nestjs/common';

import { ProductsService } from './products.service';

@Controller('products')
export class ProductController {
  constructor(private productsService: ProductsService) {}

  @Get()
  getAllProducts(): Product[] {
    // Code...
    return this.productsService.getAll();
  }
}
Enter fullscreen mode Exit fullscreen mode

Providers are ES6 classes wrapped with the @Injectable() decorator, which is imported from '@nestjs/common'.

The provider can be created using the CLI command

nest g service products

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

import { Product } from './interfaces/product.interface';

@Injectable()
export class ProductsService {
  private readonly products: Product[] = [];

  getAll(): Product[] {
    // Some code...
    return this.products;
  }

  create(product: Product) {
    // Your Code...
  }

  update(id: number) {
     // Some code...
  }

  // Other methods...
}
Enter fullscreen mode Exit fullscreen mode

Thus, the Module is a separate part of the application with isolated logic. Controller - the entry point to this Module, which is called when a request is received for a specific URL and calls the methods of the Provider. And the Provider contains all the main and additional business logic necessary for the application to function.

Thanks for your attention!

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Retry later