Nest.js có thể được coi là Angular trên phần phụ trợ vì nó cung cấp rất nhiều tính năng hữu ích và – cũng như Angular thoạt nhìn có thể hơi choáng ngợp. Để tránh quá tải thông tin, tôi sẽ bỏ qua những thông tin quan trọng nhất theo quan điểm của tôi:

  • Được xây dựng với TypeScript
  • Nhiều công nghệ được hỗ trợ ngoài (GraphQL, Redis, Elasticsearch, TypeORM, microservices, CQRS…)
  • Được xây dựng với Node.js và hỗ trợ cả Express.js và Fastify
  • Dependancy Injection
  • Mircoservice

Các khái niệm cốt lõi của Nest.js

Nếu bạn chưa quen với Nest.js, có ba khái niệm cơ bản mà bạn sẽ luôn làm việc trên đó; Module,ControllerService.

Module

Các Module đóng gói logic thành các đoạn mã (thành phần) có thể tái sử dụng.

// app.module.ts

@Module({
  imports: [],       // Other modules
  controllers: [],   // REST controllers
  providers: [],     // Services, Pipes, Guards, etc
})

export class AppModule {}

Controller

Được sử dụng để xử lý các hoạt động REST (phương thức HTTP).

// app.controller.ts

@Controller()      // Decorator indicating that the following TypeScript class is a REST controller
export class AppController {
  constructor(private readonly appService: AppService) {}    // Service available through Dependency Injection  

  @Get()     // HTTP method handler
  getHello(): string {
    return this.appService.getHello();     // Calling a service method
  }
}

Service

Các service được sử dụng để xử lý logic và chức năng. Các phương thức ở service sẽ được gọi từ bên trong controllers.

// app.service.ts

@Injectable()       // Decorator that marks a TypeScript class a provider (service)
export class AppService {
  constructor() {}       // Other services, repositories, CQRS handlers can be accessed through Dependency Injection

  getHello(): string {
    return 'Hello World!';      // Plain functionality
  }
}

Cấu trúc lại máy chủ cơ bản thành microservices

Nest.js API Gateway

Trong phần này, chúng ta sẽ chuyển đổi hai máy chủ Nest.js cơ bản thành máy chủ chính (API Gateway) và microservice

Repositories

Tác giả

Gim