Coding practice
NestJS Coding Questions
12 hands-on challenges with prompts and solution sketches for NestJS interview rounds.
Challenge set
12 coding questions
1. Controller Route
typescriptCreate a GET controller method.
@Controller("health")
export class HealthController {
@Get()
check() {
return { ok: true };
}
} 2. Injectable Service
typescriptCreate an injectable service.
@Injectable()
export class UsersService {
findAll() {
return [];
}
} 3. Module Wiring
typescriptRegister controller and provider in a module.
@Module({
controllers: [UsersController],
providers: [UsersService],
})
export class UsersModule {} 4. DTO Validation
typescriptValidate a DTO with class-validator.
export class CreateUserDto {
@IsEmail()
email!: string;
@IsString()
@MinLength(8)
password!: string;
} 5. Param Decorator
typescriptRead an id param.
@Get(":id")
findOne(@Param("id") id: string) {
return this.users.findOne(id);
} 6. Guard Stub
typescriptImplement a simple AuthGuard.
@Injectable()
export class AuthGuard implements CanActivate {
canActivate(context: ExecutionContext) {
const req = context.switchToHttp().getRequest();
return Boolean(req.headers.authorization);
}
} 7. Pipe Transform
typescriptParse an id with ParseIntPipe.
@Get(":id")
findOne(@Param("id", ParseIntPipe) id: number) {
return this.users.findOne(id);
} 8. Exception Filter
typescriptThrow a Nest HTTP exception.
if (!user) throw new NotFoundException("User not found"); 9. Config Injection
typescriptRead config with ConfigService.
constructor(private readonly config: ConfigService) {}
getPort() {
return this.config.get<number>("PORT", 3000);
} 10. Async Provider
typescriptCreate an async factory provider.
{
provide: "DB",
useFactory: async () => connect(),
} 11. Interceptor Logging
typescriptLog request duration with an interceptor.
@Injectable()
export class LoggingInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler) {
const started = Date.now();
return next.handle().pipe(tap(() => console.log(Date.now() - started)));
}
} 12. Dependency Scope
typescriptInject a request-scoped provider.
@Injectable({ scope: Scope.REQUEST })
export class RequestContext {
constructor(@Inject(REQUEST) private readonly req: Request) {}
}