> For the complete documentation index, see [llms.txt](https://blockchain-journal-hope-mabuza.gitbook.io/blockchain-journal-hope-mabuza-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://blockchain-journal-hope-mabuza.gitbook.io/blockchain-journal-hope-mabuza-docs/backend/nest.js.md).

# Nest.js

Nest.js is a Node.js framework that is used for large scale development because it separates the code for the server into modules, it also uses Typescript. It seperates requests and responses from the business logic. It uses annotations/ decorators for things.

**Choose NestJS when:**

* Your backend is large enough to need clear separation between modules, controllers, and services
* You're working in a team and need everyone following the same structure
* You're using TypeScript — NestJS is built for it, Express just tolerates it
* You need built-in support for things like dependency injection, guards, interceptors, and pipes without wiring them yourself
* You're building something production-grade — a real DApp backend, a DeFi platform, an NFT marketplace API

In Nest.js we have three main types of  class decorators. They tell Nest.js what the role of the class is.

**Modules (@Module)**\
I understand them as a configuration file that Nest.js reads before even getting to the request/response. It tells Nest.js which controller it uses, the module it uses and sometimes can inject other modules. Every feature has its own module. It has a `@Module`  annotation.\
This a a scaffold of a module class:

```typescript
@Module({
  imports: [],      // other modules this module depends on
  controllers: [],  // controllers that belong to this module
  providers: [],    // services/providers this module creates and uses
  exports: [],      // providers to share with other modules
})
export class UsersModule {}
```

**Controller (@Controller)**

The controller is the entrypoint. It takes the requests and sends the response. It should be as minimal as possible. It imports the . here is the typical structure of a controller. It uses the `@Controller`  decorator.

```typescript
import { Controller, Get, Post, Body, Param, Delete, Put } from '@nestjs/common';
import { UsersService } from './users.service';
@Controller('users')
export class UsersController {
constructor(private usersService: UsersService) {}// pass providers here as parameters
@Get()
findAll() {
return this.usersService.findAll();
}
@Get(':id')
findOne(@Param('id') id: string) {
return this.usersService.findOne(id);
}
@Post()
create(@Body() createUserDto: any) {
return this.usersService.create(createUserDto);
}
@Put(':id')
update(@Param('id') id: string, @Body() updateUserDto: any) {
return this.usersService.update(id, updateUserDto);
}
@Delete(':id')
remove(@Param('id') id: string) {
return this.usersService.remove(id);
}
}
```

> You'll notice `createUserDto: any` in the `create` and `update` methods. In production you'd replace that `any` with a **DTO (Data Transfer Object)** — a TypeScript class that describes exactly what shape the incoming JSON should be.

typescript

```typescript
export class CreateUserDto {
  username: string;
  walletAddress: string;
}
```

> If the client sends data that doesn't match, NestJS automatically rejects it with a `400 Bad Request` before it ever reaches your service. Use it on any `POST`, `PUT`, or `PATCH` endpoint.

**Injectable (@Injectable)**

Any class that has an Injectable annotation is a provider. It means it will be used by other classes. The  main provider is the Service. It holders the business logic for the routes. Here is a snippet of how it typically looks:<br>

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

@Injectable()
export class UsersService {
  findAll() {          // GET /users
    return 'all users';
  }

  findOne(id: string) {          // GET /users/:id
    return `user ${id}`;
  }

  create(createUserDto: any) {          // POST /users
    return createUserDto;
  }

  update(id: string, updateUserDto: any) {          // PUT /users/:id
    return `updated user ${id}`;
  }

  remove(id: string) {          // DELETE /users/:id
    return `deleted user ${id}`;
  }
}
```

The providers are passed as the parameter in the controller, we dont create instances of it like we on Express.js. Nest.js does that for use.&#x20;

<figure><img src="/files/oMvLOo69fWLkLclwSMuM" alt=""><figcaption></figcaption></figure>

**Getting in:**

* **Middleware** — doorman at the building entrance, doesn't care who you are, just does basic checks for everyone (logging, parsing)
* **Guard** — security desk inside, checks your ID and decides if you're allowed to proceed
* **Pipe** — form checker at the front desk, makes sure the data you brought is in the right format before anyone sees it

**Doing the work:**

* **Controller** — receptionist, receives you and figures out what you need, then calls the right person
* **Service** — the actual worker who does the job and hands back the result

**Getting out:**

* **Response** — the answer packaged up and sent back to the client
