👇 Copied (mostly) from this source.
Modules encapsulate logic into reusable pieces of code (components).
// app.module.ts
@Module({
imports: [], // Other modules
controllers: [], // REST controllers
providers: [], // Services, Pipes, Guards, etc
})
export class AppModule {}
👆 Back to top
Used to handle REST operations (HTTP methods).
// Request to <http://endpoint/users/><userId>/hi
@Controller('users') // 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('/:id/hi') // HTTP method handler
sayHi(@Param('id') userId: string): string {
return this.appService.sayHi(userId); // Calling a service method
}
}
👆 Back to top
Services -- Services are used to handle logic and functionality. Service methods are called from within a controller.
// app.service.ts
@Injectable() // Decorator that marks a TypeScript class a provider (service)
export class AppService {
constructor() {} // Other services, repositories, can use Dependency Injection
sayHi(userId: string): string {
return `Hello ${userId}`; // Plain functionality
}
}
Dependency injection -- borrow the idea from Angular.
👆 Back to top
👉 Official doc.
import { Injectable } from '@nestjs/common';
import { Cat } from './interfaces/cat.interface';
@Injectable() // <- marks the CatsService class as a provider.
export class CatsService {
private readonly cats: Cat[] = [];
findAll(): Cat[] {
return this.cats;
}
}
Then use this provider as,