DEV Community 👩‍💻👨‍💻

Cover image for NestJS - Providers
Ilya R
Ilya R

Posted on

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';

  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';

export class ProductController {
  constructor(private productsService: ProductsService) {}

  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';

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!

Top comments (0)

👀 Just want to lurk?

That's fine, you can still create an account and turn on features like 🌚 dark mode.