Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ What Are Services and Why They Matter | Services and Architecture
Building Backend Applications with Nest.js

bookWhat Are Services and Why They Matter

メニューを表示するにはスワイプしてください

Services are responsible for handling business logic in your application.

Instead of placing logic inside controllers, you move it into services to keep your code organized and easier to maintain.

A controller should only:

  • Receive the request;
  • Call the appropriate service;
  • Return the response.

All processing and data handling should happen inside a service.

Here is an example:

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

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

The @Injectable() decorator tells Nest.js that this class can be used as a service.

Now use this service inside a 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.getAllUsers();
  }
}

  • UsersService: contains the logic;
  • UsersController: calls the service;
  • The controller does not handle data directly.

This separation makes your code cleaner and easier to scale.

question mark

What is the main purpose of a service in Nest.js?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 3.  1

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 3.  1
some-alt