Skip to content

Service

Pablodeibar edited this page Jan 9, 2024 · 14 revisions

Adding a Service in Your NestJS Application

Introduction

When adding a new service to your NestJS application, it's essential to follow a structured approach. This guide outlines the necessary steps to create a service, including the creation of a controller, service, module, and any additional components specific to the service.

Prerequisites

Before you begin, make sure you have the following:

  • Node.js installed on your machine.
  • A NestJS application set up.

Step-by-Step Guide

1. Create Service Components

Navigate to the src/services/your-service folder in your NestJS project and create the following components for your new service:

  • Controller: Handles incoming requests and communicates with the service.
  • Service: Contains the business logic and interacts with external APIs or databases.
  • DTO (Data Transfer Object): Captures the data sent by the API of the service.

2. Import Service Module

In the src/services/your-service folder, create a module file (e.g., your-service.module.ts) and import your service components.

// your-service.module.ts

import { Module } from '@nestjs/common';
import { YourServiceController } from './your-service.controller';
import { YourServiceService } from './your-service.service';

@Module({
  controllers: [YourServiceController],
  providers: [YourServiceService],
})
export class YourServiceModule {}

3. Add DTO for the Service

Create a DTO to capture the data sent by the API of your service. For example, a GitHub service DTO may look like this:

import { ApiProperty } from "@nestjs/swagger";

export class GithubDto {
    @ApiProperty({ description: 'GitHub user ID' })
    id: number;
  
    @ApiProperty({ description: 'GitHub display name', required: false })
    displayName?: string;
  
    @ApiProperty({ description: 'GitHub username' })
    username: string;
  
    @ApiProperty({ description: 'GitHub profile URL' })
    profileUrl: string;
  
    @ApiProperty({ description: 'GitHub user photos', type: [String], required: false })
    photos?: string[];
  
    @ApiProperty({ description: 'GitHub provider', default: 'github' })
    provider: string;
  
    @ApiProperty({ description: 'Raw GitHub user data as a JSON string' })
    _raw: string;
  
    @ApiProperty({ description: 'GitHub user data as JSON object' })
    _json: Record<string, any>;
  
    @ApiProperty({ description: 'GitHub access token' })
    accessToken: string;
}

4. Create a Strategy

In the src/strategy folder, create a strategy file (e.g., your-service.strategy.ts). This file should contain the strategy for your service, including the client ID and secret and the scopes that you are going to need for the action / reaction like reading an email, acces to the user informations etc.

// your-service.strategy.ts

import { ReplaceWithStrategy } from 'replace-with-package'; // Replace with actual import

export class YourServiceStrategy extends ReplaceWithStrategy {
  constructor() {
    super({
    clientID: 'replace-with-your-client-id',
    clientSecret: 'replace-with-your-client-secret',
    // Add any additional strategy options
    });
  }
}

5. Implement Guard

In the src/guards folder, create a guard file (e.g., your-service-oauth.guard.ts). This guard handles the authentication process for your service.

// your-service-oauth.guard.ts

import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class YourServiceOAuthGuard extends AuthGuard('your-service') {
  constructor(private configService: ConfigService) {
    super({
      // Customize guard options if needed
    });
  }
}

6. Configure Module in Main Services

Now, it's time to integrate your newly created service module into the main services module.

  1. Open the services.module.ts file in the root of your NestJS project.

  2. Import the module you created in Step 2 (YourServiceModule in this example).

   // services.module.ts

   import { Module } from '@nestjs/common';
   import { YourServiceModule } from './services/your-service/your-service.module';

   @Module({
     imports: [YourServiceModule],
     // Other module configurations
   })
   export class ServicesModule {}
  1. Ensure that the imports array includes your service module (YourServiceModule). This step enables NestJS to recognize and use the components from your service in the main services.

  2. Save the changes to the services.module.ts file.

With these steps, your NestJS services is now configured to use the service you added. Remember to replace placeholder names with your actual service names and configurations.

Feel free to adjust the instructions based on your specific service module and naming conventions.