Key concepts

👇 Copied (mostly) from this source.

Modules

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

Controllers

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

Providers

👆 Back to top

Standard providers

👉 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,