import { Controller, Get, UseGuards } from '@nestjs/common'; import { AuthGuard } from '@nestjs/passport'; @Controller('items') export class ItemsController { @Get() @UseGuards(AuthGuard('jwt')) findAll() { return { message: 'Items fetched' }; } }
The @Get decorator defines an HTTP GET endpoint. The @UseGuards with AuthGuard('jwt') protects the route, allowing only authenticated requests. If authentication succeeds, the method returns the JSON with status 200 OK.
import { createParamDecorator, ExecutionContext } from '@nestjs/common'; export const CurrentUser = createParamDecorator((data: unknown, ctx: ExecutionContext) => { const request = ctx.switchToHttp().getRequest(); return request.user; }); @Controller('profile') export class ProfileController { @Get() getProfile(@CurrentUser() user) { return user; } }
The createParamDecorator function is the correct way to create a custom parameter decorator in NestJS. It accesses the request object via ExecutionContext and returns the user property.
import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { User } from './user.entity'; @Injectable() export class UserService { constructor(@InjectRepository(User) private userRepository: Repository<User>) {} findAll() { return this.userRepository.find(); } }
When injecting a repository, you must use @InjectRepository(Entity) on the constructor parameter. Without it, NestJS cannot resolve the dependency.
import { Injectable, OnModuleInit } from '@nestjs/common'; @Injectable() export class AppService implements OnModuleInit { onModuleInit() { console.log('Module initialized'); } }
The onModuleInit() method is called once after all providers in the module have been initialized, allowing setup logic after injection.
Decorators in NestJS add metadata that the framework reads to perform dependency injection, routing, and module organization. They do not execute code immediately or generate schemas automatically.