NestJS Services 詳解:サービスの作成と注入及びビジネスロジックの管理
- 1053単語
 - 5分
 - 08 Jul, 2024
 
サービス(Services)は、NestJSにおける重要な概念の一つで、アプリケーションのビジネスロジックを管理するために使用されます。本文では、NestJSのサービス概念について詳しく説明し、サービスの作成と注入の方法、およびサービスを通じてビジネスロジックを管理する方法を紹介します。
サービスの概要
サービス(Services)は、ビジネスロジックをカプセル化して管理するためのクラスです。NestJSでは、サービスは通常、依存性注入(Dependency Injection)メカニズムを通じて使用されます。サービスは、コントローラや他のサービス、モジュールに注入され、ビジネスロジックの再利用と分離を提供します。
サービスの作成
NestJSでは、サービスの作成は非常に簡単です。NestJS CLIを使用してサービスを生成することもできますし、手動でサービスを作成することもできます。以下は、NestJS CLIを使用してサービスを作成する例です:
1nest generate service users上記のコマンドは、UsersServiceファイルを生成します。以下の内容を追加します:
1import { Injectable } from "@nestjs/common";2
3@Injectable()4export class UsersService {5  private readonly users = [];6
7  findAll() {8    return this.users;9  }10
11  findOne(id: string) {12    return this.users.find((user) => user.id === id);13  }14
15  create(user) {16    this.users.push(user);17  }18
19  update(id: string, user) {20    const existingUser = this.findOne(id);21    if (existingUser) {22      Object.assign(existingUser, user);23    }24  }25
26  remove(id: string) {27    const index = this.users.findIndex((user) => user.id === id);28    if (index !== -1) {29      this.users.splice(index, 1);30    }31  }32}上記の例では、UsersServiceは@Injectable()デコレーターを持つクラスです。このデコレーターは、このクラスが注入可能なサービスであることをNestJSに伝えます。
サービスの注入
NestJSでは、サービスは依存性注入によってコントローラや他のサービスに注入することができます。以下は、UsersServiceをUsersControllerに注入する例です:
1import {2  Controller,3  Get,4  Post,5  Put,6  Delete,7  Param,8  Body,9} from "@nestjs/common";10import { UsersService } from "./users.service";11
12@Controller("users")13export class UsersController {14  constructor(private readonly usersService: UsersService) {}15
16  @Get()17  findAll() {18    return this.usersService.findAll();19  }20
21  @Get(":id")22  findOne(@Param("id") id: string) {23    return this.usersService.findOne(id);24  }25
26  @Post()27  create(@Body() createUserDto: CreateUserDto) {28    return this.usersService.create(createUserDto);29  }30
31  @Put(":id")32  update(@Param("id") id: string, @Body() updateUserDto: UpdateUserDto) {33    return this.usersService.update(id, updateUserDto);34  }35
36  @Delete(":id")37  remove(@Param("id") id: string) {38    return this.usersService.remove(id);39  }40}上記の例では、UsersControllerのコンストラクタにUsersServiceを注入しています。この方法により、コントローラのメソッド内でサービスが提供するビジネスロジックを使用することができます。
ビジネスロジックの管理
サービスはビジネスロジックをカプセル化して管理し、コントローラから分離することで、コードをモジュール化し、メンテナンスしやすくします。以下はいくつかの一般的なビジネスロジック管理の例です:
データストレージの処理
サービスは、データの保存および取得操作(例:データベースからのデータのクエリや保存)を処理するために使用できます。以下は、ユーザーデータの保存を処理する例です:
1import { Injectable } from "@nestjs/common";2import { User } from "./user.entity";3
4@Injectable()5export class UsersService {6  private readonly users: User[] = [];7
8  findAll(): User[] {9    return this.users;10  }11
12  findOne(id: string): User {13    return this.users.find((user) => user.id === id);14  }15
16  create(user: User) {17    this.users.push(user);18  }19
20  update(id: string, user: User) {21    const existingUser = this.findOne(id);22    if (existingUser) {23      Object.assign(existingUser, user);24    }25  }26
27  remove(id: string) {28    const index = this.users.findIndex((user) => user.id === id);29    if (index !== -1) {30      this.users.splice(index, 1);31    }32  }33}ビジネスルールの処理
サービスは、複雑なビジネスルールやロジック(例:割引の計算、ユーザー入力の検証)を処理するために使用できます。以下は、ユーザーの検証を処理する例です:
1import { Injectable } from "@nestjs/common";2
3@Injectable()4export class AuthService {5  validateUser(username: string, password: string): boolean {6    // 仮定としてここにユーザーリストがあります7    const users = [{ username: "test", password: "password" }];8
9    const user = users.find(10      (user) => user.username === username && user.password === password,11    );12    return !!user;13  }14}外部APIの呼び出し
サービスは、HTTPリクエストを介してデータを取得したり、サードパーティサービスとやり取りするために外部APIを呼び出すためにも使用できます。以下は、外部APIを呼び出す例です:
1import { Injectable, HttpService } from "@nestjs/common";2import { map } from "rxjs/operators";3
4@Injectable()5export class ExternalApiService {6  constructor(private readonly httpService: HttpService) {}7
8  fetchData() {9    return this.httpService10      .get("https://api.example.com/data")11      .pipe(map((response) => response.data));12  }13}まとめ
本文では、NestJSにおけるサービス(Services)の概念について詳しく説明し、サービスの作成と注入の方法、およびサービスを通じてビジネスロジックを管理する方法を紹介しました。サービスは、NestJSにおいて重要な役割を果たしており、ビジネスロジックをカプセル化することで、コードをモジュール化し、メンテナンスしやすくします。