<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Tamim Ikbal</title>
    <description>The latest articles on DEV Community by Tamim Ikbal (@tamim_ikbal).</description>
    <link>https://dev.to/tamim_ikbal</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F2500853%2Ff1750215-7a38-49f7-85c0-1e6dc28c16f5.jpg</url>
      <title>DEV Community: Tamim Ikbal</title>
      <link>https://dev.to/tamim_ikbal</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/tamim_ikbal"/>
    <language>en</language>
    <item>
      <title>Finding the Peak Index in a Mountain Array</title>
      <dc:creator>Tamim Ikbal</dc:creator>
      <pubDate>Tue, 04 Feb 2025 07:53:56 +0000</pubDate>
      <link>https://dev.to/tamim_ikbal/find-peak-index-of-a-mountain-array-23cm</link>
      <guid>https://dev.to/tamim_ikbal/find-peak-index-of-a-mountain-array-23cm</guid>
      <description>&lt;p&gt;Hello, my friends! Hope you’re all doing great. Today, we’ll solve the problem of finding a Peak Element in a Mountain Array.&lt;/p&gt;

&lt;h4&gt;
  
  
  Here is my submission on LeetCode.
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fflxa78ac50lkvtjm843a.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fflxa78ac50lkvtjm843a.png" alt="Leetcode Submission Image" width="713" height="707"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  What is a Peak Element?
&lt;/h3&gt;

&lt;p&gt;A peak element in an array is an element that is greater than both of its neighbors. Simply put, if array[i] is the peak, then:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;array[i - 1] &amp;lt; array[i] &amp;amp;&amp;amp; array[i] &amp;gt; array[i + 1]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To optimize the search, I use Binary Search to maintain efficient time complexity, moving left or right based on the mid value.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Edge Case&lt;/strong&gt;: If the array length is 1 or less (&lt;code&gt;array.length &amp;lt;= 1&lt;/code&gt;), we return the 0 index.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Edge Case&lt;/strong&gt;: If the first element is greater than the next (&lt;code&gt;array[0] &amp;gt; array[1]&lt;/code&gt;), we return 0, since the first index is the peak index.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Edge Case&lt;/strong&gt;: If the last element is greater than the previous (&lt;code&gt;array[array.length - 1] &amp;gt; array[array.length - 2]&lt;/code&gt;), we return array.length - 1, as the last element is the peak.&lt;/li&gt;
&lt;li&gt;Now, if array[mid - 1] &amp;lt; array[mid] &amp;amp;&amp;amp; array[mid] &amp;gt; array[mid + 1], we return mid, because it's the peak element, being greater than its neighbors.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Else If&lt;/strong&gt;: array[mid] &amp;gt; array[mid - 1], we move right since array[mid] is greater than the left element, meaning the peak lies to the right.&lt;/li&gt;
&lt;li&gt;Else: We move left, as mid is greater than the right element.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Let's Code
&lt;/h3&gt;

&lt;p&gt;I will code in JavaScript to find the peak element and implement Binary Search for an optimized solution.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var findPeakElement = function (nums) {
  let length = nums.length;

  if (1 &amp;gt;= length) {
    return 0;
  }

  if (nums[0] &amp;gt; nums[1]) {
    return 0;
  }

  if (nums[length - 1] &amp;gt; nums[length - 2]) {
    return length - 1;
  }

  let left = 1;
  let right = length - 2;
  while (left &amp;lt;= right) {
    let mid = Math.floor((left + right) / 2);

    if (nums[mid - 1] &amp;lt; nums[mid] &amp;amp;&amp;amp; nums[mid] &amp;gt; nums[mid + 1]) {
      return mid;
    } else if (nums[mid] &amp;gt; nums[mid - 1]) {
      left = mid + 1;
    } else {
      right = mid - 1;
    }
  }

  return -1;
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run Some Test:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.log(findPeakElement([1, 2, 3, 1])); // Index: 2, Element: 3
console.log(findPeakElement([1, 2, 1, 3, 5, 6, 4])); // Index: 5, Element: 6
console.log(findPeakElement([1])); // Index: 0, Element: 1
console.log(findPeakElement([3, 4, 3, 2, 1])); // Index: 1, Element: 4
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can try this problem: &lt;a href="https://leetcode.com/problems/find-peak-element/" rel="noopener noreferrer"&gt;Leetcode&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Thanks for reading.&lt;/p&gt;

</description>
      <category>algorithms</category>
      <category>dsa</category>
    </item>
    <item>
      <title>Setup Validation Pipes &amp; Yup for NestJS Request Validation.</title>
      <dc:creator>Tamim Ikbal</dc:creator>
      <pubDate>Mon, 03 Feb 2025 17:10:48 +0000</pubDate>
      <link>https://dev.to/tamim_ikbal/setup-validation-pipes-and-yup-to-validate-nestjs-request-5ejm</link>
      <guid>https://dev.to/tamim_ikbal/setup-validation-pipes-and-yup-to-validate-nestjs-request-5ejm</guid>
      <description>&lt;p&gt;Hello my friends, Hope you are all doing well. Today we will set up a Validation Pipes to validate Requests based on the Yup Validation rule schema. Let’s Code.&lt;/p&gt;

&lt;h3&gt;
  
  
  1. Creating our NestJS Project
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm i -g @nestjs/cli
nest new project-name
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  2. Install YUP
&lt;/h3&gt;

&lt;p&gt;Yup is a powerful schema builder for runtime value parsing and validation. So in this article, we will use Yup for validation.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm i yup
yarn add yup
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  3. Create The Todo DTO And Validation Schema
&lt;/h3&gt;

&lt;p&gt;Let's say we have an application where we require a Title and Description.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { object, string, InferType } from 'yup';

export const createTodoSchema = object({
  title: string().min(3).required(),
  description: string().required(),
});

export type createTodoDto = InferType&amp;lt;typeof createTodoSchema&amp;gt;;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here we created a Yup object with a set of validation rules and export then we generated and export the todo DTO &lt;code&gt;createTodoDto&lt;/code&gt; from &lt;code&gt;createTodoSchema&lt;/code&gt;;&lt;/p&gt;

&lt;h3&gt;
  
  
  4. Create A Validator Pipes
&lt;/h3&gt;

&lt;p&gt;Now, We have to create a Validation Pipes with will validate the Request based on our giver YUP Object.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;validator.pipes.ts&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import {
    ArgumentMetadata,
    HttpException,
    HttpStatus,
    Injectable,
    PipeTransform,
  } from '@nestjs/common';
  import { Schema, ValidationError } from 'yup';

  @Injectable()
  export class Validator implements PipeTransform {
    constructor(private schema: Schema) {}

    transform(value: any, metadata: ArgumentMetadata) {
      try {
        //Validate the request input data based on the Validation rule..
        return this.schema.validateSync(value, { abortEarly: false });
      } catch (error) {

        //When got error from YUP catch it and process the errors.
        if (error instanceof ValidationError) {
          const errors = {};

          //Formate the errors
          error.inner.forEach((err: ValidationError) =&amp;gt; {
            const path = err.path || '';
            const messages = errors[path] || [];
            errors[path] = [err.message, ...messages];
          });

          //Throw the Exceptoom with The errors and Status code 422.
          throw new HttpException(
            {
              message: 'Validation failed',
              errors: errors,
            },
            HttpStatus.UNPROCESSABLE_ENTITY,
          );
        }

        //Cache rest of the errors and throw it with 500 server error.
        throw new HttpException(
          {
            message: 'Something went wrong',
          },
          HttpStatus.INTERNAL_SERVER_ERROR,
        );
      }
    }
  }

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, we create a class &lt;code&gt;Validator&lt;/code&gt; which is a custom Nestjs pipes (&lt;a href="https://docs.nestjs.com/pipes" rel="noopener noreferrer"&gt;read more about pipes&lt;/a&gt;). &lt;br&gt;
In the &lt;code&gt;constructor&lt;/code&gt; function we initiated the YUP schema.&lt;br&gt;
Now, As we implement the &lt;code&gt;PipeTransform&lt;/code&gt; interface, we have to use  &lt;code&gt;transform&lt;/code&gt; method and which will be called By Nestjs automatically.&lt;/p&gt;
&lt;h4&gt;
  
  
  On validation failed
&lt;/h4&gt;

&lt;p&gt;Given system will throw the error with this formate.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "message": "Validation failed",
  "errors": {
    "title": [
      "title is a required field",
      "title must be at least 3 characters"
    ],
    "description": [
      "description is a required field"
    ]
  }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  5. Use the Validator Pipe
&lt;/h3&gt;

&lt;p&gt;Let’s validate the request of &lt;code&gt;store&lt;/code&gt; method.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;todo.controller.ts&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Body, Controller, Get, Post, UsePipes } from '@nestjs/common';
import { TodoService } from './todo.service';
import { Todo } from './todo.interface';
import { createTodoDto, createTodoSchema } from './dto/create.dto';
import { Validator } from '../../Pipes/validator.pipe';

@Controller('todos')
export class TodoController {
  constructor(private readonly todoService: TodoService) {}

  @Get()
  async index(): Promise&amp;lt;Todo[]&amp;gt; {
    return await this.todoService.findAll();
  }

  @Post()
  //We can use our Custom Validator Pipes with Nestjs @UsePipes decorator. 

  @UsePipes(new Validator(createTodoSchema))
  async store(@Body() todoDto: createTodoDto): Promise&amp;lt;ApiResponse&amp;lt;Todo&amp;gt;&amp;gt; {
    console.log(todoDto);
    const todo = await this.todoService.create(todoDto);
    return {
      message: 'Todo Created Updated!',
      payload: todo,
    };
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Explanation&lt;/strong&gt;: In the @UsePipes decorator we passed our Validator class instance with the &lt;code&gt;createTodoSchema&lt;/code&gt; schema and the Validator class will validate the request with defines rull on &lt;code&gt;createTodoSchema&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;todo.service.ts&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Injectable } from '@nestjs/common';
import { Repository } from 'typeorm';
import { Todo } from './todo.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { createTodoDto } from './dto/create.dto';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class TodoService {
  constructor(
    @InjectRepository(Todo)
    private todoRepository: Repository&amp;lt;Todo&amp;gt;,
    private config: ConfigService,
  ) {}

  findAll(): Promise&amp;lt;Todo[]&amp;gt; {
    console.log(this.config.get('app.name'));
    return this.todoRepository.find();
  }

  create(todoDto: createTodoDto): Promise&amp;lt;Todo&amp;gt; {
    const todo = new Todo();
    todo.title = todoDto.title;
    return this.todoRepository.save(todo);
  }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Thanks for reading. If you want to read more about Custom Pipes please read the Nestjs official docs &lt;a href="https://docs.nestjs.com/pipes#custom-pipes" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>nestjs</category>
      <category>yup</category>
    </item>
    <item>
      <title>How to Set Up Custom Configuration Files in NestJS</title>
      <dc:creator>Tamim Ikbal</dc:creator>
      <pubDate>Sun, 02 Feb 2025 04:54:18 +0000</pubDate>
      <link>https://dev.to/tamim_ikbal/how-to-setup-custom-configuration-files-intonestjs-288a</link>
      <guid>https://dev.to/tamim_ikbal/how-to-setup-custom-configuration-files-intonestjs-288a</guid>
      <description>&lt;p&gt;Hello my friends, I Hope you are all doing well. Today we will learn how to set up the custom config file in nestjs.&lt;/p&gt;

&lt;p&gt;NestJS is a powerful JavaScript framework that provides all the essential functionalities needed for building scalable applications. However, it's not fully structured, you need to organize it yourself. While NestJS provides recommendations, it's up to us to implement a clean and maintainable configuration setup.&lt;/p&gt;

&lt;p&gt;In this guide, we will set up a custom configuration file to keep our application settings structured and easy to manage. Let’s get started!&lt;/p&gt;

&lt;p&gt;Let's say you have an env file with some different type of variable, for example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;APP_NAME=Laravel
APP_ENV=local
APP_TIMEZONE=UTC

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, We can get and use them by process.env in our js code which is not ideal for production because of performance, security, and caching.&lt;/p&gt;

&lt;p&gt;So, let’s create a config file for them but here also we shouldn't tie them into one file then we will break SRP and this will be harder to manage. So, let's do this step by step.&lt;/p&gt;

&lt;h3&gt;
  
  
  1. Creating our NestJS Project
&lt;/h3&gt;

&lt;p&gt;To create a NestJs project, we need to run the following commands in our terminal.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm i -g @nestjs/cli
nest new project-name
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  2. Install Nestjs Config
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm i --save @nestjs/config
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  3. Make the configuration file
&lt;/h3&gt;

&lt;p&gt;Create the respective configuration files in the &lt;code&gt;src/config&lt;/code&gt; folder. In this case, &lt;code&gt;app.config.js&lt;/code&gt; and &lt;code&gt;database.config.js&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  4. Write the Config File
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;app.config.js&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import * as process from 'node:process';
import { registerAs } from '@nestjs/config';

const config = () =&amp;gt; ({
  name: process.env.APP_NAME || 'NestApp',
  env: process.env.APP_ENV || 'production',
  debug: process.env.APP_DEBUG === 'true',
  timezone: process.env.APP_TIMEZONE || 'UTC',
  locale: process.env.APP_LOCALE || 'en',
});

export default registerAs('app', config);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;database.config.js&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import * as process from 'node:process';
import { registerAs } from '@nestjs/config';

const config = () =&amp;gt; ({
  database: process.env.DB_CONNECTION || 'mysql',
  connection: {
    mysql: {
      type: 'mysql',
      host: process.env.DB_HOST || 'localhost',
      port: parseInt(process.env.DB_PORT, 10) || 3306,
      username: process.env.DB_USERNAME || 'root',
      password: process.env.DB_PASSWORD || '',
      database: process.env.DB_NAME || '',
      entities: ['./../Models/*.entity{.ts,.js}'],
      migrations: ['./../database/migrations/*{.ts,.js}'],
      synchronize: false,
      migrationsRun: false,
      logging: process.env.DB_LOGGING === 'true',
    },
  },
});

export default registerAs('database', config);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h5&gt;
  
  
  Explanation
&lt;/h5&gt;

&lt;p&gt;We define a configuration object and export it using nestjs registerAs(), which provides a namespace (prefix) for the configuration to avoid conflict between config key.&lt;/p&gt;

&lt;h3&gt;
  
  
  5. Import and Setup the ConfigModule
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;app.module.ts&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import appConfig from './config/app.config';
import databaseConfig from './config/database.config';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true, // Makes config accessible throughout the application
      load: [appConfig, databaseConfig],
    }),
  ],
  controllers: [],
  providers: [],
})
export class AppModule {}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  6. Using Config Values in the Application
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;app.service.ts&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class AppService {
  constructor(private config: ConfigService) {}

  getHello(): string {
    console.log(this.config.get('app.name')); // Fetching APP_NAME from config
    return 'Hello World!';
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That’s it! Now you have a powerful and organized configuration setup in NestJS. 🚀&lt;/p&gt;

&lt;p&gt;Thanks for reading! 🙌&lt;/p&gt;

&lt;p&gt;To Read more about Nest COnfig Please Visit: &lt;code&gt;https://docs.nestjs.com/techniques/configuration&lt;/code&gt;&lt;/p&gt;

</description>
      <category>nestjs</category>
    </item>
  </channel>
</rss>
