NESTJS: TUTORIAL BÁSICO PARA CREAR APLICACIONES
NestJS es un framework para Node que permite crear aplicaciones del lado del servidor que sean eficientes, escalables y mantenibles. Está fuertemente inspirado en Angular, utiliza TypeScript por defecto y se basa en conceptos como Módulos, Controladores y Services.
Requisitos previos
- NodeJS (v18 o superior recomendado)
- npm o yarn
- Conocimientos básicos de TypeScript y Express aunque no son obligatorios, pero ayudan
Instalación
Instalar la CLI de NestJS globalmente:
npm install -g @nestjs/cli
Verificar la instalación:
Crear un nuevo proyecto
El CLI te preguntará si se quiere usar npm o yarn. Elegir el que se prefiera y entrar a la carpeta del proyecto:
Estructura básica del proyecto
src/
├── app.controller.spec.ts
├── app.controller.ts
├── app.module.ts
├── app.service.ts
├── main.ts
- "main.ts": Punto de entrada de la aplicación
- "app.module.ts": Módulo raíz
- "app.controller.ts": Controlador (maneja las rutas HTTP)
- "app.service.ts": Servicio (lógica de negocio)
Entendiendo los conceptos básicos
main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
}
bootstrap();
app.module.ts
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
@Module({
imports: [],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
app.controller.ts
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello(): string {
return this.appService.getHello();
}
}
app.service.ts
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return '¡Hola Mundo! Bienvenido a NestJS';
}
}
Ejecutar la aplicación
Introducir la url "http://localhost:3000" en el navegador y se debería mostrar el mensaje "¡Hola Mundo! Bienvenido a NestJS".
Crear un controlador y servicio nuevo (ejemplo: Usuarios)
Endpoint para usuarios:
nest generate controller users
nest generate service users
//Forma abreviada
nest g co users
nest g s users
"users.controller.ts"
import { Controller, Get, Post, Body, Param, Delete } from '@nestjs/common';
import { UsersService } from './users.service';
@Controller('users')
export class UsersController {
constructor(private readonly usersService: UsersService) {}
@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);
}
@Delete(':id')
remove(@Param('id') id: string) {
return this.usersService.remove(+id);
}
}
"users.service.ts"
import { Injectable } from '@nestjs/common';
@Injectable()
export class UsersService {
private users = [
{ id: 1, name: 'Juan Pérez', email: 'juan@example.com' },
{ id: 2, name: 'María López', email: 'maria@example.com' },
];
findAll() {
return this.users;
}
findOne(id: number) {
return this.users.find(user => user.id === id);
}
create(createUserDto: any) {
const newUser = {
id: this.users.length + 1,
...createUserDto,
};
this.users.push(newUser);
return newUser;
}
remove(id: number) {
const index = this.users.findIndex(user => user.id === id);
if (index !== -1) {
return this.users.splice(index, 1)[0];
}
return null;
}
}
Agregar el nuevo controlador y servicio al fichero "AppModule"
import { UsersController } from './users/users.controller';
import { UsersService } from './users/users.service';
@Module({
controllers: [AppController, UsersController],
providers: [AppService, UsersService],
})
Probar los endpoints
Con "npm run start:dev corriendo":
- GET "http://localhost:3000/users"
- GET "http://localhost:3000/users/1"
- POST "http://localhost:3000/users"