Nest JS: Create a new Provider / Service

Creating a new Service / Provider in the nest JS app. How to create a Service / Provider in nest JS?

Providers in Nest JS also known as services are basically responsible for executing the business logic. In the Nest JS Service we use @Injectable decorator for the purpose of dependency injection.

Creating a new Service in Nest JS – ( Manual way )

For example, here we are creating a service for the auth functionality of our app.

  • In the src folder create folder named auth
  • Inside the auth folder we can create the module file : auth.service.ts
  •  Creating a new  Service in Nest JS - ( Manual way )

    auth.service.ts

    import { Injectable } from "@nestjs/common";
    
    @Injectable({})
    export class AuthService {}
    Nest JS: Create a new Provider / Service

    Adding the provider to the module

    app.module.ts

    import { Module } from '@nestjs/common'
    import { AuthController } from './auth.controller';
    import { AuthService } from './auth.service';
    @Module({
        controllers: [AuthController],
        providers: [AuthService]
        
    })
    export class AuthModule { }
    nest js Adding the provider to the module

    Dependency injection: Connecting Provider to the controller

    auth.controller.ts

    import { Controller, Post } from "@nestjs/common";
    import { AuthService } from "./auth.service";
    
    @Controller('auth')
    export class AuthController{
        constructor(private authService: AuthService) {}
        @Post('signup')
        signup() {
            return this.authService.signup()
        }
        @Post('login')
        login() {
            return this.authService.login()
        }
    }

    auth.service.ts

    import { Injectable } from "@nestjs/common";
    
    @Injectable({})
    export class AuthService {
        signup(){
            return { msg: 'I have signed up!'};
        }
    
        login(){
            return { msg: 'I have logged in..!'};
        }
    }

    Result:

    Login POST request
    Signup POST request

    About the Author: smartcoder

    You might like

    Leave a Reply

    Your email address will not be published. Required fields are marked *