≡ Menu

Welcome to the world of NestJS!

If you’re looking to build efficient, scalable, and maintainable server-side applications, you’ve come to the right place.

NestJS is a progressive Node.js framework heavily inspired by Angular, providing an out-of-the-box architecture for enterprise-grade backends.

In this tutorial, we’ll walk through the basics of setting up a NestJS project and creating your first API endpoint.

Why Choose NestJS?

  • TypeScript by Default: Brings static typing and improved code quality.

  • Modular Architecture: Keeps your application organized as it grows.

  • Powerful CLI: Speeds up development by generating boilerplate code.

  • Scalability: Designed specifically for large-scale applications.


Prerequisites

Make sure you have the following installed:

  1. Node.js (LTS version recommended)

  2. npm (comes with Node)


Step 1: Install the NestJS CLI

The CLI allows you to generate modules, controllers, and services with simple commands. Open your terminal and run:

npm i -g @nestjs/cli

Step 2: Create a New Project

Navigate to your desired folder and run:

nest new my-nest-app

Select npm as your package manager. Once finished, move into the project:

cd my-nest-app

Step 3: Run the Application

To start the development server with “watch mode” (which restarts whenever you save a file), run:

npm run start:dev

Your app is now running at http://localhost:3000. You should see “Hello World!” in your browser.


Step 4: Building a “To-Do” API

Let’s build a functional API. We will generate a Module, a Controller (to handle requests), and a Service (to handle logic).

1. Generate the Files

Run these commands in your terminal:

nest g module todos
nest g controller todos
nest g service todos

2. Implement the Service

Open src/todos/todos.service.ts and replace the code with this logic to manage a simple array:

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

interface Todo {
  id: number;
  title: string;
  completed: boolean;
}

@Injectable()
export class TodosService {
  private todos: Todo[] = [];
  private nextId = 1;

  findAll(): Todo[] {
    return this.todos;
  }

  create(title: string): Todo {
    const newTodo = { id: this.nextId++, title, completed: false };
    this.todos.push(newTodo);
    return newTodo;
  }

  findOne(id: number): Todo {
    return this.todos.find(todo => todo.id === id);
  }
}

3. Implement the Controller

Open src/todos/todos.controller.ts and update it to handle HTTP requests:

import { Controller, Get, Post, Body, Param } from '@nestjs/common';
import { TodosService } from './todos.service';

@Controller('todos')
export class TodosController {
  constructor(private readonly todosService: TodosService) {}

  @Get()
  getAll() {
    return this.todosService.findAll();
  }

  @Post()
  create(@Body('title') title: string) {
    return this.todosService.create(title);
  }

  @Get(':id')
  getOne(@Param('id') id: string) {
    return this.todosService.findOne(+id);
  }
}

Step 5: Test Your API

You can use a tool like Postman or Insomnia to test your new endpoints:

  1. POST http://localhost:3000/todos with a JSON body: {"title": "Learn NestJS"}.

  2. GET http://localhost:3000/todos to see your list.

Conclusion

You’ve just built a working REST API with NestJS!

From here, you can explore database integration with TypeORM, add Validation Pipes, or implement JWT Authentication.

Useful links below:

Let me & my team build you a money making website/blog for your business https://bit.ly/tnrwebsite_service

Get Bluehost hosting for as little as $1.99/month (save 75%)…https://bit.ly/3C1fZd2

Best email marketing automation solution on the market! http://www.aweber.com/?373860

Build high converting sales funnels with a few simple clicks of your mouse! https://bit.ly/484YV29

Join my Patreon for one-on-one coaching and help with your coding…https://www.patreon.com/c/TyronneRatcliff

Buy me a coffee ☕️https://buymeacoffee.com/tyronneratcliff

{ 0 comments }

If you’ve ever seen a “Maximum call stack size exceeded” error in your console, you’ve met the Call Stack.

But what is it exactly, and how does it handle complex tasks without freezing your browser?

To understand JavaScript performance, you have to look past the syntax and into the engine. Let’s break down the two most important pieces of the puzzle: the Call Stack and the Event Loop.


1. What is the Call Stack?

In simple terms, the Call Stack is the mechanism JavaScript uses to keep track of its place in a script. It tells the engine what function is currently running and what functions are called from within that function.

How It Works: LIFO

The Call Stack operates on a LIFO (Last In, First Out) principle. Imagine a stack of physical books:

  • You add a book to the top (Push).

  • You can only remove the book that is currently on the top (Pop).

The Lifecycle of a Function Call

When you run a JavaScript file, the engine creates a Global Execution Context. As it encounters functions, it follows these steps:

  1. Push: When a function is invoked, it is added to the top of the stack.

  2. Execute: The engine runs the code inside that function.

  3. Pop: Once the function returns a value or finishes, it is removed from the stack.


2. A Real-World Example

Let’s look at how the stack handles this snippet:

function greet() {
  sayHi();
  console.log("Back in greet");
}

function sayHi() {
  console.log("Hi!");
}

greet();

The Execution Flow:

  1. greet() is called => Added to stack.

  2. Inside greet, sayHi() is called => Added to top of stack.

  3. sayHi executes console.log("Hi!").

  4. sayHi finishes => Popped off the stack.

  5. Control returns to greet, which executes console.log("Back in greet").

  6. greet finishes => Popped off the stack.


3. The “Single-Threaded” Limitation

Because there is only one Call Stack, JavaScript is single-threaded.

It can only do one thing at a time.

If a function at the top of the stack takes a long time to run (like a massive calculation), it “blocks” the stack.

This is why a website might feel “frozen”—the Call Stack is busy and can’t handle your clicks.

What is a Stack Overflow?

A stack overflow happens when a function calls itself (recursion) without an exit strategy.

The stack grows until it hits the browser’s memory limit.

function recurse() {
  recurse(); 
}
recurse(); // Uncaught RangeError: Maximum call stack size exceeded

4. The Event Loop: Handling Asynchronous Magic

If JavaScript can only do one thing at a time, how does it handle network requests (fetch) or timers without freezing?

This is where the Event Loop, Web APIs, and the Callback Queue come in.

Step 1: Web APIs

When you call an asynchronous function like setTimeout, JavaScript doesn’t wait for it. It hands the task to the browser’s Web APIs and moves to the next line of code immediately.

Step 2: The Callback Queue

Once the Web API finishes its task (e.g., the 2-second timer ends), the callback function is sent to the Callback Queue. It sits there, waiting for its turn to run.

Step 3: The Event Loop

The Event Loop is a constant monitor. It has one specific rule:

“If the Call Stack is empty, take the first task from the Callback Queue and push it onto the Stack.”

Example in Action:

console.log("Start");

setTimeout(() => {
  console.log("Callback");
}, 0);

console.log("End");

Output:

  1. Start

  2. End

  3. Callback

Even with a 0ms delay, “Callback” prints last. Why? Because the Event Loop had to wait for the Call Stack to be completely empty (after “End” was logged) before it could move the callback from the queue to the stack.


Summary

  • Call Stack: Manages the order of execution (LIFO).

  • Single-Threaded: JavaScript handles one task at a time.

  • Web APIs: Handle heavy lifting (timers, requests) outside the main thread.

  • Event Loop: Coordinates between the stack and the queue to keep things running smoothly.

Useful links below:

Let me & my team build you a money making website/blog for your business https://bit.ly/tnrwebsite_service

Get Bluehost hosting for as little as $1.99/month (save 75%)…https://bit.ly/3C1fZd2

Best email marketing automation solution on the market! http://www.aweber.com/?373860

Build high converting sales funnels with a few simple clicks of your mouse! https://bit.ly/484YV29

Join my Patreon for one-on-one coaching and help with your coding…https://www.patreon.com/c/TyronneRatcliff

Buy me a coffee ☕️https://buymeacoffee.com/tyronneratcliff

 

{ 0 comments }