Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Moving Logic from Controller to Service | Section
Building Backend Applications with Nest.js

bookMoving Logic from Controller to Service

Свайпніть щоб показати меню

At first, it is common to place logic directly inside a controller. This works for simple cases, but quickly becomes hard to manage as the application grows.

Here is an example of logic inside a controller:

@Controller('users')
export class UsersController {
  @Get()
  getUsers() {
    return ['Alice', 'Bob'];
  }
}

This approach mixes request handling and business logic in one place.

To improve this, move the logic into a service.

Create a service:

import { Injectable } from '@nestjs/common';

@Injectable()
export class UsersService {
  getUsers() {
    return ['Alice', 'Bob'];
  }
}

Now update the controller:

import { Controller, Get } from '@nestjs/common';
import { UsersService } from './users.service';

@Controller('users')
export class UsersController {
  constructor(private usersService: UsersService) {}

  @Get()
  getUsers() {
    return this.usersService.getUsers();
  }
}

Here is what changed:

  • The controller no longer contains data or logic;
  • The service handles all processing;
  • The controller only calls the service and returns the result.

This separation makes your code easier to read, test, and extend.

question mark

Why should logic be moved from controllers to services?

Виберіть правильну відповідь

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 1. Розділ 11

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

Секція 1. Розділ 11
some-alt