NestJS Services 詳解:創建和注入服務及管理業務邏輯
- 975字
- 5分鐘
- 2024-07-08
服務(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
服務還可以用於調用外部 API,例如通過 HTTP 請求獲取數據或與第三方服務進行交互。以下是一個調用外部 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 中起到了至關重要的作用,它們用於封裝業務邏輯,使代碼更加模塊化和可維護。