Модули, контроллеры и сервисы
Разберитесь в основных компонентах: как модули организуют код, контроллеры обрабатывают запросы, а сервисы инкапсулируют бизнес-логику.
«Модули, контроллеры и сервисы» — бесплатный урок NestJS Enterprise Backend APIs на CoddyKit. Это урок 3 из 3. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения NestJS Enterprise Backend APIs, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс NestJS Enterprise Backend APIs содержит 3 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
NestJS Building Blocks
A NestJS app is built from three core blocks — Modules, Controllers, and Services — that organize code, handle requests, and hold logic.
Organizing with Modules
A Module (class with @Module()) is a feature group: it bundles related controllers and services and defines their dependency scope.
Your First NestJS Module
This AppModule shows the @Module() decorator declaring a controller and a service, making them available within its scope.
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
@Module({
imports: [], // Other modules this module needs
controllers: [AppController], // Controllers handled by this module
providers: [AppService], // Services (providers) available in this module
exports: [], // Providers to export for other modules
})
export class AppModule {}Controllers: Handling Requests
Controllers (classes with @Controller()) handle incoming HTTP requests and return responses, delegating the heavy logic to services.
A Simple API Endpoint
This AppController uses @Get() to handle GET requests at /, calling AppService for the actual message.
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
@Controller() // Optional path prefix, e.g., '@Controller('users')'
export class AppController {
constructor(private readonly appService: AppService) {}
@Get() // Handles GET requests to '/' (or '/users' if prefix exists)
getHello(): string {
return this.appService.getHello();
}
}Services: Business Logic Hub
Services (providers marked @Injectable()) hold your business logic and DB calls — reusable units injected into controllers to keep them lean.
Your Logic in a Service
This AppService exposes a method for the controller to call. The @Injectable() decorator lets NestJS manage it via DI.
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello from NestJS!';
}
}Connecting the Dots
Dependency Injection wires it together: declare the parts in a module, ask for the service in the controller's constructor, and Nest injects it.
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
console.log('NestJS application is running on http://localhost:3000');
}
bootstrap();
// When you visit http://localhost:3000,
// AppController's getHello() is called,
// which in turn calls AppService's getHello().Component Roles Check
You've learned about Modules, Controllers, and Services. How well do you understand their primary roles?
Core Components Summary
You learned the core trio: Modules organize, Controllers handle requests, Services hold logic — all connected through DI. TypeORM next!
Часто задаваемые вопросы
Урок «Модули, контроллеры и сервисы» бесплатный?
Да — полный текст урока «Модули, контроллеры и сервисы» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс NestJS Enterprise Backend APIs, подпишись на CoddyKit PRO. Курс NestJS Enterprise Backend APIs содержит 3 уроков всего.
Чему я научусь в уроке «Модули, контроллеры и сервисы»?
Разберитесь в основных компонентах: как модули организуют код, контроллеры обрабатывают запросы, а сервисы инкапсулируют бизнес-логику. Ты практикуешь NestJS Enterprise Backend APIs с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать NestJS Enterprise Backend APIs?
Предыдущий опыт не требуется. NestJS Enterprise Backend APIs на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 3.
Сколько времени занимает урок «Модули, контроллеры и сервисы»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке NestJS Enterprise Backend APIs?
Да. Каждый урок NestJS Enterprise Backend APIs включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Введение во фреймворк NestJS
- Структура проекта и CLI
- Модули, контроллеры и сервисы